A list,
1.1 What is Axios
Axios is a Promise-based HTTP library that can be used in browsers and Node.js.Copy the code
1.2 features
- The browser initiates the XMLHttpRequests request
- The Node sends an HTTP request
- Supporting Promise API
- Listen for requests and returns
- Transform the request and return
- Cancel the request
- Automatically convert JSON data
- Client support defense
Second, the Axios
2.1 installation
npm install axios --save
Copy the code
Or use CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy the code
2.2 Basic Usage
Get request:
axios.get('/user', {
params: {
name: 'klivitam'
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error)
}
Copy the code
Post request:
axios.post('/user',{
name:'klivitam',
address:'china'
})
.then(function(response){
console.log(response);
})
.catch(function(error){
console.log(error);
});
Copy the code
Concurrent operation:
function getUserAccount() {return axios.get('/user/12345');
}
function getUserPermissions() {return axios.get('/user/12345/permissions');
}
axios.all([getUerAccount(),getUserPermissions()])
.then(axios.spread(function(acc, PERS){// Both requests are now complete});Copy the code
2.3 Requesting API Configuration
Axios has the ability to make a few Settings when making a request, as follows:
axios({
method:'post',
url:'/user/12345',
data:{
name:'klivitam',
address:'china'}});Copy the code
2.4 Request Settings
In a request configuration, only the URL is required, and if not specified, the default is a Get request
{// 'url' is a server link used to request a URL:'/user'Method: 'get', // 'baseURL' if 'url' is not an absolute address, then it will be preceded by it. // This is handy when axios uses relative addresses // in the example baseURL:'http://some-domain.com/api/', // 'transformRequest' allows requested data to be transformed before being sent to the server. // This also supports the 'PUT', 'GET', 'PATCH' methods. // The last function in the array must return a string, an 'ArrayBuffer', or 'Stream' transformRequest:[function(data){// Process the requested data according to your own requirementsreturndata; }], // 'transformResponse' allows returned data to be passed inthen/catch before processing transformResponse:[function(data){// Process the data as neededreturndata; }], // 'headers' is a custom header to be sent.'X-Requested-with':'XMLHttpRequest'}, // 'params' is the request parameter in the request connection and must be a pure object, or the URLSearchParams object params:{ID:12345}, //' paramsSerializer 'is an optional function that is used to serialize parameters // for example: (https://ww.npmjs.com/package/qs, http://api.jquery.com/jquery.param/) paramsSerializer:function(params){
return Qs.stringify(params,{arrayFormat:'brackets'})}, // 'data' is the data that needs to be set // only applicable to applications'PUT'.'POST'.'PATCH'Request method // When 'transformRequest' is not set, it must be of one of the following types (non-repeatable?). : / / - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams / / - only the browser: FormData, File, Blob / / - only the Node: Stream data:{ firstName:'fred'}, // 'timeout' defines the request time in milliseconds. // If the request time exceeds this set time, the request will stop. Timeout :1000, // 'withCredentials' indicates whether the request is cross-domain, // The credentials should be used with withCredentials:false// Default // adapter adapter, which allows custom processing of requests, makes testing easier. // Return a promise and provide validation returns (see [Response docs](# the response - API))
adapter:function(config){ /*... */}, // 'auth' indicates that HTTP-based authentication should be used and certificates provided. // This sets an authorization header and overrides the authorization header you set in the header. auth:{ username:'janedoe',
password:'s00pers3cret'}, // 'responseType' indicates the data types returned by the server. These types should be set to //'arraybuffer'.'blob'.'document'.'json'.'text',stream' responsetype:'json', // 'xsrfHeaderName' is the name of the HTTP header that carries the XSRF value xrsfHeadername:'.X-XSRF-TOKEN', // Default // 'onUploadProgress' allows events to handle the upload process. Function (progressEvent){// what you want to do when a local process event happens}, // 'onDownloadProgress' allows handling of events for the download process: Function (progressEvent){function(progressEvent){// 'maxContentLength' defines the maximum amount of content to return from HTTP. 2000, // 'validateStatus' defines promise resolve and reject. // HTTP returns a status code. If 'validateStatus' returns true (or null/undefined), PROMISE will accept. Other promises will be rejected. validateStatus: function(status){ return status >= 200 && stauts < 300; // Default}, // 'httpAgent' and 'httpsAgent' define a custom proxy when an HTTP or HTTPS request is generated, respectively, in nodeJS. // This allows setting a few options, such as' keepAlive '- this is disabled by default. HttpAgent: new http.Agent({keepAlive:treu}), httpsAgent: new https.Agent({keepAlive:true}), // 'proxy' defines the host name and port number of the server. // 'auth' indicates that HTTP basic authentication should be connected to 'proxy' and provide a certificate. // This will set a 'Proxy-Authorization'header, overriding the original custom. Proxy :{host:127.0.0.1, port:9000, auth:{username:'cdd', password:'123456'}}, // 'cancelTaken' defines a Cancellation that can be used to cancel the request // (see details of Cancellation below) cancelToke: new CancelToken(function(cancel){})}Copy the code
2.5 Response Data Response
The return of a request contains the following information
Data {}, // 'status' is the HTTP status code returned by the server, //' statusText 'is the HTTP status information returned by the server statusText:'ok'Headers :{}, // 'config' is set to axios to request config:{}}Copy the code
2.6 Interceptors
You can intercept requests or returns before they are processed by then or catch.
Adding interceptors:
/ / add a request interceptor axios. Interceptors. Request. Use (function(config){// Do something before the request is sentreturn config;
},function(error){// Do something when a request error occursreturnPromise.reject(error); }); / / add a return interceptor axios. Interceptors. Response. Use (function(Response){// Do some processing on the returned datareturn response;
},function(error){// Do some processing on the returned errorreturn Promise.reject(error);
});
Copy the code
Remove interceptors:
var myInterceptor = axios.interceptors.request.use(function() {/ *... * /}); axios.interceptors.rquest.eject(myInterceptor);Copy the code
Third, cross-domain
Because in the development stage of Vue, it is basically packaged and compiled with Webpack, and node environment needs to run locally, so the domain name of running is local localhost. At this time, calling the back-end interface involves cross-domain problems.Copy the code
3.1 ProxyTable
Vue’s proxyTable is a tool for cross-domain configuration at development stage. It can configure multiple backend servers to cross request interfaces at the same time. The real NPM package it relies on is HTTP-proxy-Middleware, which has richer configuration on GitHub and can be configured on demand
Without considering the back-end CROS cross-domain scheme, the use of front-end configuration ProxyTable to implement cross-domain request is as follows:
- findconfig/index.jsIn the file
proxyTable:{}
The modified
proxyTable: {
'/api': {
target: 'https://tasst.sinoxk.cn', // This is the address you want to delegate (development interface address).true// Cross-domain needs to add this pathRewrite: {'^/api': ' '}}}Copy the code
ProxyTable supports multiple interfaces:
proxyTable: {
'/api': {
target: 'https://tasst.sinoxk.cn', // This is the address you want to delegate (development interface address).true// Cross-domain needs to add this pathRewrite: {'^/api': ' '}}};'/service': {
target: 'https://tasst.sinoxk.cn', // This is the address you want to delegate (development interface address).true// Cross-domain needs to add this pathRewrite: {'^/service': ' '}}}Copy the code
- findconfig/dev.env.jsFile, configuration
BASE_URL
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
BASE_URL:'"/api"'// Development environment domain name})Copy the code
- findconfig/prod.env.jsFile, configuration
BASE_URL
module.exports = {
NODE_ENV: '"production"',
BASE_URL:'"https://asst.sinoxk.com"'// The production environment keeps the official domain name}Copy the code
- Configure the underlying domain name for Axios
axios.defaults.baseURL = process.env.BASE_URL
Copy the code
After modifying all configuration files, you need to restart the environment
npm run dev / npm run start
Copy the code
Four, encapsulation
In the daily project development process, we need to use the network library when we interact with the background to obtain data. Usually, in the vUE project, we use the AXIOS library to do a secondary encapsulation based on our own project business
4.1 Preparations
On the UI light prompt component, the Toast component (Vant document) in the Vant library is selected, and the SPECIFIC UI framework to be used can be selected according to actual needs
Install: NPM install vant --saveCopy the code
Data serialization, if there is a practical need for the project, can use QS, here to make a brief introduction
Install: NPM install qs --saveCopy the code
Qs. stringify and json. stringify are used and distinguished
Qs.stringify () serializes the object into a URL, concatenated with & json. stringify converts the object into a JSON stringCopy the code
Usage:
var a = {name:'xiaoming',age:10}
qs.stringify(a); //log: 'name=xiaoming&age=10'
JSON.stringify(a) //log: '{"name":"hehe","age":10}'
Copy the code
Based on the separation of the underlying configuration and the business interface, a new folder httpServer is created in the SRC directory, along with new ajax.js and api.js files
Ajax.js: a secondary wrapper of AXIos that acts as the base network library, adding the base configurationCopy the code
Api.js: Manages the output of the actual business base interface of the project and the processing of the returned response dataCopy the code
In the daily project module, based on multi-person development, of course, on the basis of api.js, business can be extended according to the functional module, such as
Xiaoming is responsible for the list module business. Create api-list.js and import api.js.... // in api-list.js: import API from'./api'
export default {
getList(url,params){
api.get(url,params)
}
}
Copy the code
For a specific project, you can re-establish base.js to manage multiple interface domain names when multiple domain names may be configured
base.js:
/** ** const base = {sq:'https://xxxx111111.com/api/v1',
bd: 'http://xxxxx22222.com/api'
}
export default base;
Copy the code
Of course, in this case, based on the basis of api.js, combined with the multiple interface domain names of base.js, it is recommended to encapsulate the basic interface output according to each individual domain name, such as sq-api.js and BD-api.js
4.2 AXIos Encapsulation (Single Domain Name)
SRC/main. Js file:
import Vue from 'vue'
import App from './App'
import router from './router'
import Api from './httpServer/api'// Mount vue. Prototype to the global properties of vue.$https = Api
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
Copy the code
SRC/httpServer/ajax. Js file:
import axios from 'axios'
import {Toast} from 'vant'Const ajax = axios.create({timeout:60000, baseURL: process.env.base_url // base domain name}) /** * request blocker * before each request, If there is a token is carried in the request header token * / ajax interceptors. Request. Use (config = > {/ / judgment token (intercept) according to actual conditionreturnconfig; }, Error = > Promise. The error (error))/response interceptor * * * * / ajax interceptors. Response. Use (a/res/request success = > res. Status = = = 200? Promise.resolve(res) : Promise.reject(res), error => { const {response} = error;ifToast({message: response.message}) {// The request has been sent, but it is not in the scope of 2xx.return Promise.reject(response);
} else// Network state controls the display of a global disconnection prompt component in app.vue. // About the refresh of the disconnection component to retrieve data, {message: Toast({message:'Network desertion, please try again later'}); }})export default ajax;
Copy the code
For the configuration of process.env.base_URL, in the development environment, it needs to be accessed as a proxy:
//config/dev.env.js
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
BASE_URL:'"/api"'// process the API})Copy the code
//config/prod.env.js
'use strict'
module.exports = {
NODE_ENV: '"production"',
BASE_URL:'"https://www.xxx.com"'// The production environment does not need to handle}Copy the code
//config/index.js
...
proxyTable: {
'/api': {
target: 'https://tasst.sinoxk.cn',// Back end interface address changeOrigin:true,// whether to allow crossing pathRewrite: {'^/api': ' ',// override (interface address with API will be replaced)},}},...Copy the code
SRC/httpServer/API. Js file:
import ajax from './ajax'
import {Toast} from 'vant'/** */ const handleResponse = (res, success, failure) => {switch (res.code) {case200: // success && success(res.data);break;
case401: // The login token is invalidbreak;
default:
if (failure) {
failure(res);
} else {
Toast({message:res.msg || 'Request failed, please try again later! '});
}
break; }}export default {
get: function (url, params, success, failure) {
ajax.get(url, {
params: params
}).then(res => {
if(res.status == 200) { handleResponse(res.data.data, success, failure); }}); }, post:function (url, params, success, failure) {
ajax.post(url, params).then(res => {
if(res.status == 200) { handleResponse(res.data.data, success, failure); }}}})Copy the code
In the SRC/components/HelloWorld. Vue file use:
<script>
export default {
name: 'HelloWorld'.data() {
return {
msg: 'Welcome to Your Vue.js App'}},created() {// Request interface data this.$https.get('/xkzx/member/service', {
pageNum: 1,
pageSize: 10
}, function(data) {// success console.log(data); },function(res) {// failed})}} </script>Copy the code
Full project example: VUE-AJAX (netease News Interface)