Preface
During the development process, we often need to access the server, but each request needs to be accessed again, which is too troublesome, so we encapsulate a method for making requests here and apiize the interface. When it needs to be used, it is very simple to use.
1. What is axios?
axios is aPromiseThe HTTP library can be used in browsers and .
axios is an HTTP client based on Promise for browsers and nodejs. It is essentially an encapsulation of native XHR, but it is an implementation version of Promise, complies with the latest ES specifications and has the following characteristics:
- Create XMLHttpRequests from the browser
- Create http request from
- Support Promise API
- Intercept requests and responses
- Convert request data and response data
- Cancel request
- Automatically convert JSON data
- Client-supported defense XSRF
2. API interface encapsulation steps
1. Create an interceptor ()
The code is as follows (example):
import axios from "axios";//Native axios//For intercepting["Content-Type"] = "application/json;charset=utf-8"; //Create a single caseconst http= ({ baseURL:'The first half of the interface is added to the port', timeout:5000,//Response time // headers:{"Content-Type":"application/json;charset=utf-8"}, }) //Interceptor - Request for interception(config=>{ //Some interfaces require token let token=('token'); if(token){ =token; // ={ // 'token':token // } } return config; },err=>{ return (err) }) //Interceptor - Response Intercept(res=>{ if(===2000){ return () // Here readers can modify the data returned by the server by themselves }else{ return () } },err=>{ return (err) }); //Overall exportexport default http;
2. Create a file that stores the API ()
The code is as follows (example):
//Import the interceptor as a wholeimport request from '@/'//Import the already written interceptor // Encapsulate all API interfaces export function Login(params){ (params) return request({ url:'/administrator/login', method :'post', params:params, }) } export function getRoles(params={}){ return request({ url:'/Roles/select', method :'post', params:params, }) }
3. How to use
The code is as follows (example):
import { Login } from "@/api/" //Introduce methods as needed Login(Requestparameters).then((res) => { if ( === 2000) { this.$message({ message: 'Login successfully!', type: 'success', duration: 1500 }); setTimeout(() => { let token= ; ("token",token); //If you need to store the token, you can store it here this.$('/index'); // Here you can go to the specified route }, 1550); } else { this.$message({ type: 'info', message: , duration: 1500 }); } }).catch((err) => { (err) })
Summarize
This is the end of this article about the packaging of Vue project API interface. For more related content about the packaging of Vue project API interface, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!