The directory structure is as follows
request
request.js
api.js
Copy the code
The steps in request.js are as follows
Import axios import aixos form ‘axios’; 2. Create an axios instance
const instance = axios.create({
baseURL:'xxxxxx';
}
Copy the code
Request and response interception
The purpose of the request interceptor is to perform some operations before the request is sent, such as adding tokens to each request body, which is processed uniformly and easy to change later.
/ / request intercept request information (configuration) axios. Interceptors. Request. Use (function (config) {/ / handle the request before the configuration of the return config}, Function (error) {return promise.reject (error)})Copy the code
The purpose of the response interceptor is to perform some actions upon receiving the response, such as jumping to the login page when the server returns that the login status is invalid and needs to log in again.
/ / response to intercept (configuration request return information) axios. Interceptors. Response. Use (function (response) {/ / handle the response data return response}, Error () {return promise.reject (error)})Copy the code
4. Export axios instance export default instance;
The steps in api.js are as follows
Js import request from ‘./request’; Const a = () => request.get (‘/ interface url’) 3. Export method a Export default a
Refer to method A in the page where the interface needs to be called
a().then((res) =>{
console.log(res);
}).catch((error) =>{
console.log(error);
})
Copy the code