Axios is an AJAX class library wrapped around Promise

Config Basic configuration data Headers response header request Native XHR instance Status /statusText HTTP status/status descriptionCopy the code
< script SRC = ". / node_modules/axios/dist/axios. Min. Js "> < / script > / / axios is based on the promise encapsulation AJAX libraries axios.get('./1.json').then(res=>{ console.log(res); });Copy the code

Analyze the axios

  • BaseURL: unified basic address

    • axios.defaults.baseURL = ‘liuqi.cn1.utools.club’;
  • Uniformly configure the request header

    • Headers. Post Adds a headers to a POST request
    • axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;
  • Add headers for all requests to Headers.com mon

    • axios.defaults.headers.common[‘Content-Type’] = ‘application/x-www-form-urlencoded’;
  • The transformRequest calls a processing parameter before the POST request, and the return value is passed to the background in the request body

  • TransformRequest allows you to modify the request data before sending it to the server

  • This can only be used with the ‘PUT’, ‘POST’ and ‘PATCH’ request methods

    • axios.defaults.transformRequest = function (data, headers) { console.log(data, headers);
  • A place to unify the processing of parameters

    • return JSON.stringify(data); };
// axios.post('/user/add', {id: 21, name: 34}). Then (res => {}); // axios.post('127.0.0.1:8888/user/add', {id: 21, name: 34}). Then (res => {}); / / when the address is HTTP or HTTPS, beginning with its own address, it doesn't matter with baseURL / / axios. Post (' http://127.0.0.1:8888/user/add '{id: 21, name: 34 }).then(res => { }); axios.post('/user/add', { id: 21, name: 34 }, { }).then(res => { });Copy the code
  • Add a request interceptor
Axios. Defaults. Interceptors. Resquest. Use (function success (config) {/ / do something before sending a request the console. The log (config); return config; }, function error(error) {// What to do about the request error console.log(error); console.log(error); return Promise.reject(error); })Copy the code
  • Add a response interceptor
Axios. Defaults. Interceptors. Response. Use (function onSuccess (response) {/ / do something the console. The response data log (response); return response; }, function onFail(error) {return promise.reject (error); });Copy the code

Pass the second parameter after the path, which is an object that has a Params object in it, and put the parameter in the params object

 axios.get('./1.json',{params:{id:1}}).then(res=>{});
Copy the code

Post: The second parameter is directly sent to the background

axios.post('./1.json',{id:1}).then(res=>{})
Copy the code

Axios manual encapsulation

BaseURL my_axios.defaults = {baseURL: ""}; function my_axios(options) { let { method = 'get', url, params, data, headers } = options; Return new Promise((resolve, reject) => {method = method.toupperCase (); // Handle the address if (url.indexof (' HTTP ')! == 0) { url = my_axios.defaults.baseURL + url; }; If (method === 'get ') {if (url.indexof ('? ') > -1) { url += '&' + Qs.stringify(params); } else { url += '? ' + Qs.stringify(params); }; }; let xhr = new XMLHttpRequest; xhr.open(method, url); ForEach (key => {xhr.setrequesTheader (key, headers[key]); // Set the request header object.keys (headers). }); xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status >= 200 && xhr.status < 400) { let test = xhr.responseText; Parse (test),// request: XHR,// XHR config: ",//axios headers: ",// status: Xhr. status,//HTTP status code statusText: xhr.statusText// status description}; resolve(data); } else if (xhr.readyState === 4 && xhr.status >= 400) { reject(xhr.response); }; }; xhr.send(data ? JSON.stringify(data) : null); }); }; My_axios.defaults. baseURL = "; my_axios({ method: 'get', url: './1.json', params: { id:1}, data:{name:'haha'}, headers: {} }).then(res => { console.log(res); });Copy the code

fetch

// fetch syntax fetch('./data.json'). Then (response=>{// Response contains information returned by the server; Response body information response. Body [ReadableStream readable flow information], we need to make readable flow information specified format / / + response. The prototype. The json/text/blob/arrayBuffer... // + Executing any of these methods will return an instance of a Promise: If the response body information can be normally translated into the specified format, the state of the promise will be fulfilled, and the value will be the data content that is transformed. If the transformation cannot be fulfilled, the state will be failed.... Return response.json() // console.log(response); }).then(value=>{ console.log(value); //["zhufengpeixun"] });Copy the code

The difference between Fetch and Axios:

  • They both send data
  • Axios is an AJAX class library based on the Promise wrapper
  • Fetch is a browser-native API
  • The pass parameter fields are different. Axios is placed in params or data, while fetch is placed in body
  • The Node environment does not support FETCH. You need to import the Node-FETCH file to support fetch
  • Configuration and interceptors in AXIos are missing from FETCH.