This is the second day of my participation in the More text Challenge. For more details, see more text Challenge
In normal project development, interface request cannot be avoided. At this time, it is possible to encapsulate a set of request methods that you are accustomed to, which can help you improve efficiency and save code repetition rate in development.
What is Axios?
First things first: Axios is not a new technology. Axios is a Promise-based HTTP client for browsers and NodeJS. It’s essentially a wrapper around native XHR, but it’s an implementation of Promise that complies with the latest ES specification.
What are the features of Axios?
- Create XMLHttpRequests from the browser
- Create an HTTP request from Node.js
- Supporting Promise API
- Intercept requests and responses
- Transform request data and response data
- Cancel the request
- Automatically convert JSON data
- The client supports XSRF defense
Begin to use
Install using NPM:
$ npm install axios
Copy the code
Install using Bower:
$ bower install axios
Copy the code
Use the CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy the code
Encapsulation Axios
Set baseURl and create config.js file
Export const baseUrl = location.protocol + '//localhost' // Project domain name const environment = process.env.node_env === 'production' ? 'pro' : Let exports = {if(environment === 'dev'){exports = {proxyBaseUrl:'/ API ', Else if(environment === 'pro'){exports = {// exports used multiple domain names, Can be multiple inlet configuration proxyBaseUrl: location protocol + '/ / localhost', / / application 1 fyBaseUrl: location protocol + '/ / localhost/application / 2}} export default exportsCopy the code
Create service.js
Configure axiOS, globally set request information and error information handling
import axios from 'axios' import router from './.. /router' const showStatus = (status) => { let message = '' switch (status) { case 400: Message = 'Request error (400)' Break Case 401: Message =' Unauthorized, please log in again (401)' Break Case 402: Message = 'Access denied (402)' Break Case 404: Message = 'request error (404)' break case 408: Message =' request timeout (408)' Break case 500: Message = 'server error (500)' break case 501: Message = 'service not implemented (501)' break Case 502: Message =' Network error (502)' Break Case 503: Message = 'Service not available (503)' Break Case 504: Message = 'network timeout (504)' break case 505: message = 'HTTP version not supported (505)' Break default: message =' Connection error (${status})! '} return '${message}, please check the network or contact administrator! } const service = axios.create({get: {' content-type ': 'application/x-www-form-urlencoded '; charset=utf-8' }, post: { 'Content-Type': 'application/x-www-form-urlencoded; Charset = utF-8 '}}, // Whether cross-site access control request withCredentials: true, timeout: Return resolve, reject () {return resolve, reject () {return resolve, In exception handling in business code return true}}) / / request interceptor service. The interceptors. Request. Use (config = > {return config}, (err) => {err.message = 'The server is abnormal, please contact the administrator! '/ / error code to the business return Promise. Reject (err)}) / / response interceptor service. The interceptors. Response. Use (response = > {const status = response.status let msg = '' if (status < 200 || status >= 300 && status ! = 401 && status ! = 500) {// Handle HTTP errors, If (typeof Response. data === 'string') {response.data = {MSG}} else { response.data.msg = msg } return response }else if(status == 200){ return response }else if(status == 500){ msg = showStatus(status) response.data = {msg:msg} router.replace({name:'exception',query:{type:500}}) return response } }, (err)=>{err.message = 'Request timeout or server exception, please check the network or contact administrator! ' return Promise.reject(err) } ) export default serviceCopy the code
3. Create the interface request file
Different blocks of functional data can create multiple files for easy differentiation and later management
Import config from './config' // base path import service from './service' // Encapsulate axios /** * data is post pass ** / export const Upload = (data)=> service({ url: `${config.proxyBaseUrl}/user/upload`, method: 'POST', data: Data, headers:{// you can set headers},})Copy the code
4. Call requests in the actual component
Then ((res)=>{// return data}).catch((err)=>{// error message}).Copy the code