Axios

Refer to the link: www.jianshu.com/p/7a9fbcbb1… Install NPM init-y: initialize a configuration file; NPM install axios –save: create dependencies; NPM install axios –save-dev: development dependency;

Package. json: configuration file; Record which modules the project relies on;

After you download Axios, you need to import Axios:

<script src="./node_modules/axios/dist/axios.js"></script>
Copy the code

Axios is based on the PROMISE HTTP client for browsers and Node.js

The characteristics of

  • Supports browsers and Node.js
  • Supporting promise
  • Intercepts requests and responses
  • Ability to transform request and response data
  • Can cancel request
  • Automatically convert JSON data
  • Browser-side support against CSRF(Cross-site request Forgery)

axios().then

Axios returns an instance of a promise by default; You can call the.then method;

axios.get("index.css").then(function(data){
	console.log(data);
}).catch(function () {
	console.log(100);
})
Copy the code

You can see that the data we requested is not on data, it is rewrapped, data.data is the data we requested;

axios.get("index.css").then(function(data){
	console.log(data.data);
}).catch(function () {
	console.log(100);
})
Copy the code

When AXIos requests data A, it places the data returned by the server on the data property of A; A catch is executed if the data request fails;

Axios request

Axios defaults to get requests;

// Initiate a GET request (GET is the default request method)
axios('/user/12345');
Copy the code

axios.get

axios.get("index.css").then(function (a) {
	// When axios requests data, it puts the data returned by the server on the data property of A;
	console.log(a.data); //a is an object
	return axios.get("/login.css");
}).then(function(data){
	// The second.then is affected by the result of the previous.then return axios.get("/login.css"); Axios.get ("/login.css") a successful request will execute/second. Then; On failure, a catch is executed;
}).catch(function () {
	console.log(100);
})
Copy the code

axios.post

axios.post("index.css")
Copy the code

axios.all

All (iterable) axios.spread(callback)

function getUserAccount() {
	return axios.get('/user/12345');
}

function getUserPermissions() {
	return axios.get('/user/12345/permissions');
}
// the argument to axios.all is an array;
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {}));Copy the code

Axios mass participation

Params: parameter of get request. Its attribute value is an object; Used to request passing parameters

axios.get("index.css", {params: {user:"a"}}).then(function (a) {
	console.log(a.data);
})
Copy the code

Post Indicates the parameter transfer of the request

axios.post("index.css", {user:"a".password:123}).then(function (a) {
	console.log(a.data);
}).catch(function () {
	console.log(100);
})
Copy the code

axios api

Requests can be made by importing the relevant configuration

axios({
  method:'post'.// The request type used in Ajax is type;
  url:'http://bit.ly/2mTM3nY', data: {username:"aaa".password:123
  }
}).then(function(response) {});Copy the code

axios.creat()

A new instance is created for each request

var instance = axios.create({
	baseURL: 'https://some-domain.com/api/'.// Base path
	timeout: 1000.headers: {'X-Custom-Header': 'foobar'}});Copy the code

Axios configures the base path

axios.defaults.baseURL = 'https://api.example.com';
axios.get("index.css").then(function () {})https://api.example.com/index.css / /
Copy the code

Configuring a Priority

Configuration items are combined according to the following rules: Request config > instance.defaults > System defaults. Those with higher priorities overwrite those with lower priorities.

// Create an instance with the default timeout of 0
var instance = axios.create();
// Reset the timeout to 2.5s with instance.defaults because the priority is higher than the system default
instance.defaults.timeout = 2500;
// Reset the timeout to 5s via request config, since the priority is higher than instance.defaults and system defaults
instance.get('/longRequest', {
	timeout: 5000
});
Copy the code

The interceptor interceptors

Axios. Interceptors. Request. Use () to block before then and catch the request and response.

// Request interception
axios.interceptors.request.use(function (config) {
	// This function is executed before the request is sent;
	// Every time a request is sent, it is intercepted;
	console.log(100);
	return config;
})
axios.get("index.css").then(function () {
	console.log(200);
})
axios.post("index.css").then(function () {
	console.log(300);
})
// The output is 100 100 300 200;
Copy the code

When a POST request and a GET request exist at the same time, the POST request is executed first and then the GET request is executed. Cause: A POST request is faster than a GET request. Both requests are asynchronous. The time of a POST request expires first, so the POST request is executed first. If you want to remove the interceptor later you can do so

var myInterceptor = axios.interceptors.request.use(function () {/ *... * /});
axios.interceptors.request.eject(myInterceptor);
Copy the code

You can also add an interceptor to the Axios instance

var instance = axios.create();
instance.interceptors.request.use(function () {/ *... * /});
Copy the code

Cancel the request

A request can be cancelled with the Cancel token; CancelToken.source

var CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios.get('/user/12345', {
	cancelToken: source.token
}).catch(function(thrown) {
	if (axios.isCancel(thrown)) {
		console.log('Request canceled', thrown.message);
	} else {
    // handle error}});// Cancel the request
source.cancel('Operation canceled by the user.');
Copy the code

fetch

Fetch is the name of an attribute in the window whose attribute value is a function that can make a request; Fetch also takes advantage of the asynchronous nature of requests — it’s based on promises. Fetch: A get request is invoked by default;

fetch("package.json", {method:"post".body:JSON.stringify({a:1.b:2}),  // Body must be passed as a string
	headers:{ // Set the request header
		'content-type':'x-www-form-urlencoded'
	},
	credentials:'include'
}).then(function (res) {
	// res.json() also returns a Promise instance; Continue. Then get its data;
	return res.json();
}).then(function (data) {
	console.log(data);// Data to be accessed;
})
Copy the code

Call the fetch function, pass in the interface URL, and return a promise. To retrieve the JSON content, we need to use the JSON () method, which also returns a Promise; The parameters of the fetch

  1. Method: indicates the HTTP request type. The default value is GET. String format;
  2. Body: HTTP request parameter; String format;
  3. Headers: HTTP request headers. Default: {}. The object format;
  4. 8. I don’t need to omit any cookies. There are also two parameters, same-origin, indicating the same origin request with cookie; Include indicates that both cross-domain and same-origin requests contain cookies.

Note: The body cannot be set in the get request.

Browsers do not support Fetch well, so they can parse the package based on Babel’s latest syntax and parse it. For better compatibility, “Fetch Pollyfill” is required.

async await

Async functions are new syntax in ES6; Making asynchronous operations more convenient. Async is represented with the keyword async and await is used inside the function.

Async functions with no await are the same as normal functions; Once await is added; Then the code under await is asynchronous;