Article directory
1 Introduction to Axios
1.1 What is Axios?
Axios is a promise -based network request library that works in
node.js
and browsers. It's isomorphic (i.e. the same set of code can run in both the browser and node.js). On the server side it uses native node.jshttp
modules, and on the client side (browser) it uses XMLHttpRequests.
1.2 Features of Axios
-
Create XMLHttpRequests from the browser
-
Create http request from node.js
-
Promise API support
-
Intercept requests and responses
-
Transform request and response data
-
cancel the request
-
Automatically convert JSON data
-
Client support for XSRF defense
2 Use of Axios
2.1 Installation of Axios
npm install axios
Enter npm install axios in the console - press Enter, when you see that there is axios in the packages of package-lock.json, it means the import is successful
2.2 Creation of Axios
2.2.1 Proxy configuration proxy
Official document portal https://cli.vuejs.org/zh/config/#devserver-proxy
2.2.1.1 Core code
const {
defineConfig } = require("@vue/cli-service")
module.exports = defineConfig({
lintOnSave: false,
transpileDependencies: true,
devServer: {
proxy: {
'/api': {
target: "http://localhost:9000", //需要跨域的目标地址
pathRewrite: {
'^/api': '' },//将带有api的路径重写为''
ws: true,//用于支持WebSocket
changeOrigin: true,//用于控制请求头的Host
},
}
}
}
)
2.2.1.2 Code Explanation
'/api' : When there is this string in the prefix of the request address, cross-domain operation will be performed, otherwise, it will be requested locally.
The prefix is like localhost:8080/api/student, where api is the prefix.
localhost:8080/student/api, the api here is not the prefix, student is his prefix
target : the address to be cross-domain, which is localhsot:5001 in the above picture
pathRewrite : path rewrite
404 error problem:
When the local server requests the server with the path of /api/student, the proxy server detects that 'api' needs to be cross-domain, and then forwards it truthfully. So when you reach port 5001, you will go to api/Student to find the resources you want, but port 5001 only has Student, so a 404 error will pop up
Using pathRewrite , the prefix in the access address will be replaced with: the following character, here is '', so when it reaches 5001, it will correctly access the Student to find the resource it wants.
changeOrigin : Host used to control the request header
The value is false, when on port 5001, when asked where the request came from, the request will truthfully answer: 8080.
The value is true, when on port 5001, when asked where the request came from, the request will lie: 5001, where are you and my answer is where .
2.2.1.3 Multiple cross domains
If you need multiple cross-domains, just continue to write down.
2.2.2 Secondary packaging of Axios
2.2.2.1 Why secondary packaging
Request interceptor, response interceptor: The request interceptor can handle some business before sending the request
When the data is returned, the response interceptor can handle some business
2.2.2.2 Axios instantiation
You can directly see 2.2.2.2.6
2.2.2.2.1 Introduction
Create a new api file and create request.js for introducing axios
2.2.2.2.2 Create axios
const requests = axios.create({
baseURL: '/api',
timeout: 50000,
});
- baseURL: Append a prefix. For example, the address you need to access is localhost:9000/api/song/SongSheet. When accessing, you only need to write 'localhost:9000/song/SongSheet'
- timeout: access timeout time in ms, exceeding this time is the access failure
2.2.2.2.3 Configure Request Interceptor
// 添加请求拦截器
requests.interceptors.request.use(function (config) {
// 在发送请求之前做些什么,例如加入token
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
This also solves a question that I have been confused about for a long time: why the data returned before has no code, but only a single data.
At one point I thought I was going to write in the backend.
If config is returned here, then there will be data , status , statusText , headers , etc. If you just return config.data, then you will only see data data.
2.2.2.2.4 Configuring Response Interceptors
requests.interceptors.response.use(function (response) {
// 在接收响应时做些什么,例如跳转到登录页
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
2.2.2.2.5 Exposure
Can't be used if it's not exposed
export default requests;
2.2.2.2.6 Examples
import axios from "axios";
const requests = axios.create({
baseURL: '/api',
timeout: 50000,
});
// 添加请求拦截器
requests.interceptors.request.use(function (config) {
// 在发送请求之前做些什么,例如加入token
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
requests.interceptors.response.use(function (response) {
// 在接收响应时做些什么,例如跳转到登录页
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
export default requests;
2.3 Direct use of Axios
The requests here is the value returned by axios.create() in 2.2, and requests need to be introduced before use
2.3.1 get request
2.3.1.1 No parameter
requests.get('url');
Example: For example, what I want to access is localhost:9000/api/song/SongAllSheet
The api is configured in baseURL, so I just need to write
requests.get('/song/SongAllSheet');
2.3.1.2 With parameters
/Opera/getPersonalOpera is the URL, value is the name of your parameter
requests.get(`/Opera/getPersonalOpera/${
value}`);
2.3.2 Post request
axios.post("url",{
params:{
name:'jok',
age:'18'
}
})
2.3.3 General (commonly used)
2.3.3.1 No parameter
get request methods: get is followed by get, post is post
requests({
url:'/Opera/getPersonalOpera',methods:'get'})
2.3.3.2 With parameters
`` is used here, in English, the key above Tab
requests({
url:`/Opera/getPersonalOpera/${
value}`,methods:'get'})
2.3.4 Examples
<template>
<div class="hello">
</div>
</template>
<script>
import requests from "@/api/request"
export default {
name: 'HelloWorld',
data() {
return{
Song: [],
secondSong:[],
thirdSong:[],
}
}, methods: {
async getAllSongs() {
let result = await requests.get('/song/SongAllSheet');
if(result.status == 200)
{
this.Song = result.data;
}
},
async getSongById(value)
{
let result = await requests({url:`/Opera/getPersonalOpera/${value}`,methods:'get'})
if(result.status == 200)
{
this.secondSong = result.data;
}
}
},
mounted() {
this.getAllSongs();
this.getSongById(1);
},
}
</script>
It can be seen that the data was successfully obtained
Solve the case where the returned data is a Promise
So you just need to assign the value directly in the method.
2.4 Unified management of interfaces
2.4.1 Reasons for unified management of interfaces
For smaller projects it doesn't hurt to use while writing
For some relatively large projects, write the interface at will. If the back-end interface is slightly changed, it will be very difficult to maintain.
So put all the interfaces together and abstract them into a method, so that you don't need to write repeatedly, and it is more convenient to change
2.4.2 Interface Management
2.4.2.1 Create a new index.js file to place the interface and introduce axios
import requests from "./request";
2.4.2.2 Writing interface methods
original
export const reqGetAllSongById = (value)=>{
return requests({
url:`/Opera/getPersonalOpera/${
value}`,methods:'get'});
}
export const reqGetAllSong = ()=>{
return requests({
url:'/Opera/getPersonalOpera',methods:'get'});
}
abbreviated version
export const reqGetAllSong = ()=>requests({
url:'/Opera/getPersonalOpera',methods:'get'});
export const reqGetAllSongByType = (value)=> requests({
url:`/Opera/getPersonalOpera/${
value}`,methods:'get'});
2.4.2.3 Interface global registration
Although this is easy to manage, if you use it, you need to introduce it one by one.
In the above position, write the following code
import * as API from '@/api'
beforeCreate(){
Vue.prototype.$API = API;
},
When using, prefix with this.$API and it can be used normally
<template>
<div class="hello">
</div>
</template>
<script>
import requests from "@/api/request"
export default {
name: 'HelloWorld',
data() {
return{
Song: [],
secondSong:[],
thirdSong:[],
}
}, methods: {
async getAllSongs()
{
let result = await this.$API.reqGetAllSongByType(1);
if(result.status==200)
{
this.Song = result.data;
}
}
},
mounted() {
this.getAllSongs();
},
}
</script>
Access is successful