current position:Home>Vue encapsulates Axios to the full version of the calling interface (code source code)
Vue encapsulates Axios to the full version of the calling interface (code source code)
2022-04-29 07:26:07【MFG_ six hundred and sixty-six】
Catalog
- First take a look at the directory you need to create , There are mainly api , utils Of request.js , main.js , vue.config.js ,view below first.vue, Here's the picture ,` Pay attention to the picture api Below request.js Change to api.js file name `
- 1. Global installation axios
- 2. establish api Below api.js This is the custom file name , The code is as follows
- 3. establish utils Below request.js This is the custom file name , The code is as follows
- 4. establish vue.config.js Of target Represents the requested domain name , Cross domain codes are as follows
- 5. Page call usage
First take a look at the directory you need to create , There are mainly api , utils Of request.js , main.js , vue.config.js ,view below first.vue, Here's the picture , Pay attention to the picture api Below request.js Change to api.js file name
1. Global installation axios
- Download plug-ins
npm install axios --save
2. And then in main.js Global mount
import axios from 'axios'
Vue.prototype.$axios = axios
2. establish api Below api.js This is the custom file name , The code is as follows
// Login interface
export const authorization_service_users_login = 'api/authorization_service/users/login'
3. establish utils Below request.js This is the custom file name , The code is as follows
Pay attention to mainly add this : find baseURL: Need to ask for
domain name
add , .com ending , for example https://baidu.com/
Download this file below
npm install js-md5 --save
npm install element-ui --save
import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import md5 from 'js-md5'
var getId = () => {
return localStorage.getItem('userId');
}
var getToken = () => {
return localStorage.getItem('token');
}
var showErr = true
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// establish axios example
const service = axios.create({
// axios The request configuration in is baseURL Options , To express a request URL Common part
baseURL: 'https://baidu.com',
// Overtime
timeout: 10000
})
// request Interceptor
service.interceptors.request.use(config => {
if (config && config.data && 'showErr' in config.data) {
showErr = config.data.showErr
}
if (config.method === 'post' && !config.data) {
config.data = {}
config.data.aid = getId()
config.data.t = new Date().getTime()
} else if (config.method === 'post' && config.data) {
config.data.aid = getId()
config.data.t = new Date().getTime()
}
if (config.method === 'post') {
config.transformRequest = (data, headers) => {
let req = JSON.stringify(data)
let token = getToken()
let sign = md5(req + token)
console.log(req + token)
config.headers['sign'] = sign
return req
}
}
if (config.method === 'get' && !config.params) {
config.params = {}
config.params.accessToken = getToken()
config.params.timeStamp = new Date().getTime()
} else if (config.method === 'get' && config.params) {
if (!config.params.accessToken) config.params.accessToken = getToken()
config.params.timeStamp = new Date().getTime()
}
// get Request mapping params Parameters
if (config.method === 'get' && config.params) {
let url = config.url + '?';
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof (value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
if (value[key] !== null && typeof (value[key]) !== 'undefined') {
let params = propName + '[' + key + ']';
let subPart = encodeURIComponent(params) + '=';
url += subPart + encodeURIComponent(value[key]) + '&';
}
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
// Response interceptors
service.interceptors.response.use(res => {
// If the status code is not set, the default status is success
const code = res.data.code;
// Get error messages
//const msg = i18n.t(`errCode.E${code}`)
const msg = res.data.msg
const flag = res.data.flag
if (!flag && (code === 401 || code === 403)) {
MessageBox.confirm(msg, ' Tips ', {
confirmButtonText: ' determine ',
cancelButtonText: ' Cancel ',
type: 'warning'
}
).then(() => {
store.dispatch('LogOut').then(() => {
this.$router.go(0)
})
}).catch(() => { });
return Promise.reject(' Login expired , Please login again ')
} else if (!flag) {
if (showErr) {
Message({
message: msg,
type: 'error'
})
}
return Promise.reject(new Error(msg))
} else {
return res.data
}
},
error => {
console.log('err' + error)
let { message } = error;
if (message == "Network Error") {
message = ' Network error ';
}
else if (message.includes("timeout")) {
message = ' Server connection timed out ';
}
else if (message.includes("Request failed with status code")) {
message = ' Network error ' + message.substr(message.length - 3);
}
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
return Promise.reject(error)
}
)
service.version = 'v1'
export default service
4. establish vue.config.js Of target Represents the requested domain name , Cross domain codes are as follows
module.exports = {
publicPath: './',
lintOnSave: false,
devServer: {
port: 8089, // Start port
open: false, // Whether to automatically open the web page after startup
proxy: {
'/api': {
target: 'https://baidu.com', //
secure: true, // Accept each other is https The interface of
ws: true, // Is it enabled? websockets
changeOrigin: true, // Whether it is allowed to cross
pathRewrite: {
'^/api': '/' // Delegate your address to this /api Use this next when requesting /api To replace your address
},
}
},
}
}
5. Page call usage
<template>
<div>
<button @click="login()"></button>
</div>
</template>
<script>
import * as api from '../../api/api'
export default {
data () {
return {
menuList: []
}
},
mounted () {
this.getList()
},
methods: {
// Login method
login (loginFrom) {
this.$refs.loginFormRef.validate(async (valid) => {
if (valid) {
request({
method: "post",
url: api.authorization_service_users_login, // introduce api File point api.js Function name inside
data: {
account: this.loginFrom.account,
password: md5(this.loginFrom.password),
},
}).then((res) => {
this.$message.success(this.$t("lang.message.loginSuccessful"));
// Save after login token state
window.localStorage.setItem("token", res.data.token);
window.localStorage.setItem("account", res.data.account);
// window.localStorage.setItem("username", res.dat);
window.localStorage.setItem("userId", res.data.userId);
// window.sessionStorage.setItem('userId',res.data.userId)
this.$router.push("/home");
});
}
});
},
}
}
</script>
If you feel the article is good, remember to pay attention and collect , If there is something wrong, please correct it , If you need to reprint , Please indicate the source , Thank you very much !!!
copyright notice
author[MFG_ six hundred and sixty-six],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204290458555594.html
The sidebar is recommended
- How to realize Ethernet wireless communication between 200smartplc?
- Still working on nginx configuration? Try this visual configuration tool. It's really powerful!
- Simple sorting of JavaScript deep copy and shallow copy
- React realizes the communication of brother components by means of message subscription and publication
- React limits props
- Java lesson 30
- Java lesson 29 136 The number 1189 appears only once Maximum number of balloons
- Simple sorting of JavaScript deep copy and shallow copy
- "Geely" new SUV is equipped with frameless doors, and the interior is more beautiful than Mercedes Benz. Can 19 universal accept it?
- Configuration of using less in react project
guess what you like
Expression used in react render
React configuration agent
JQuery sends a post request (a method of connecting PHP variables to strings)
Solve the problem that Django cannot access the local server( http://127.0.0.1:8000/ )Or the problem that the command line execution (Python 3 manage.py runserver 0.0.0.0:8000) does not respond
Summary of the writing method of react router V6
Bipeng ditch, punch in and net red, open-air boundless swimming pool, Ramada hot spring, encounter the beauty of the four seasons
JavaScript gets and modifies elements. What's wrong with not extracting the classlist attribute
Mixed mixin of Vue
Vue + element implements table filtering
Vue router2. 0
Random recommended
- Which one charges less for opening a securities account and how to open the account
- Spring MVC notes 02 domain object sharing data, view, restful, httpmessageconverter, file upload and download
- Httpclient setting timeout
- Command line / Python uses pdf2htmlex to convert PDF to HTML
- [front end three swordsmen III] analysis of JavaScript scalpel Part II
- How to choose the front-end learning path
- Finite element parametric element, calculation, theoretical problems
- Handwritten CSS modules to understand its principle
- Front end browser debugging tips
- Performance problem analysis guide for enterprise JavaScript applications running in production systems
- CSS aspect-ratio All In One
- Actual combat of vue3 project --- Zhihu daily --- details page
- Actual combat of vue3 project --- Zhihu daily --- home page function
- Great Wall Motors is falling endlessly! The boss has lost 150 billion yuan in half a year, and the performance of the new energy sector has improved
- Nginx tips batch shutdown process
- Openresty introduces nginx_ upstream_ check_ Module module
- Nginx multiple servers_ How does name match
- Why does the front end still prompt cannot post, and the error reported by the back end still prompt null pointer?
- HTML Li set margin: 50%, but the width of the outermost div is the standard
- Are there any specific steps to create a prototype, such as JavaScript?
- How does HTML5 display the value obtained from the database in the specified area
- Problems related to nginx rewriting interface
- What happens when you open a CSS file in eclipse without responding
- React download local template can be downloaded locally, but the deployment online download is blank
- @Babel / traverse official example running error: typeerror: traverse is not a function
- The click event of jQuery has no effect
- How to learn from non professional background?
- Usage of API documented as @since 1.8+ less... (Ctrl+F1) Inspection info: This inspection finds all
- Configuration Vue of webpack
- Introduction to nginx (learning notes)
- Is the financial management class of qiniu school true? Can you learn how to manage money in free lessons
- How does Java randomly get elements from a list
- Use of Vue on in Vue
- Use of Vue router
- Vue basic syntax
- Use of webpack
- Vue diff algorithm
- CSS -- Text gradient from top to bottom
- Routing: Vue router
- Leetcode 658. Find K closest elements