The difference between axios,ajax,jquery Ajax,axios and fetch __ajax

Source: Internet
Author: User
Tags auth instance method set time
Outline:

The concept of Axios installs Axios simple example Axios API Axios request configuration and Response data format Axios Interceptor Ajax,jquery Ajax,axios and Fetch differences :

The concept of Axios Axios is a promise based HTTP library that can be used in browsers and Node.js.
Characteristics:
Create a xmlhttprequests from the browser
To create an HTTP request from Node.js
Support for Promise APIs
Intercepting requests and responses
Transform request data and response data
Cancel Request
Automatically convert JSON data

Client Support Defense XSRF


2. Installation

Install Nodejs (with NPM) install CNPM (optional)
NPM install-g cnpm--registry=https://registry.npm.taobao.org
Initialize Project:
NPM init-y
NPM Way to install Axios
NPM I axios-d 3. Axios Simple Example

1), GET request

Let vueobj = this;
Axios.get (' api/goodslists ', {
Params: {"Goodsid": "01003"}
} )
. Then (function (response) {
Console.log (Response.data);
Vueobj.goodslist = Response.data; Assign the acquired data to the Goodslist
})
. catch (function (error) {
Console.log (Error);
});


2), execute multiple concurrent requests

Getall:function () {
function Getbooks () {return axios.get (' api/books '); }
function Getreaders () {return axios.get (' api/readers '); }
Axios.all ([Getbooks (), Getreaders ()]). Then (
Axios.spread (function (books, readers) {
When all two requests are complete, the function is called, the first parameter is the result of the first request, and the second is the result of the second request
Console.log (Books.data);
Console.log (Readers.data);
})
);
}

API for 4.Axios

Axios function Axios The requested alias Axios process concurrency to create an instance of the instance method

1), Axios function:

Axios (config). In the Config object parameter, all but the URL, the other optional attributes.
Axios Some settings that can be made when making a request. Such as:
Initiate GET request let vueobj = this;
Axios ({
Method: ' Get ',
URL: ' Api/goodslists ',
Params: {"Goodsid": "01003"}
})
. Then (function (response) {
Vueobj.goodslist = Response.data;
})
. catch (function (error) {
Console.log (Error);

});


2), Axios request alias:

For convenience, Axios provides rename support for all the request methods, as follows:
Axios.request (config)
Axios.get (Url[,config])
Axios.delete (Url[,config])
Axios.head (Url[,config])
Axios.post (Url[,data[,config]])
Axios.put (Url[,data[,config]])
Axios.patch (Url[,data[,config]])

1, axios.request (config)

Let vueobj = this;
Axios.request ({
Method: ' Get ',
URL: ' Api/goodslists ',
params:{"Goodsid": "01002"}
})
. Then (function (response) {
Vueobj.goodslist = Response.data;
})
. catch (function (error) {
Console.log (Error);
});

2. Axios.get (Url[,config])

Let vueobj = this;
Axios.get (' api/goodslists ', {
params:{
"Goodsid": "01003"
}
})
. Then (function (response) {
Vueobj.goodslist = Response.data;
})
. catch (function (error) {
Console.log (Error);
});

3. Axios processing concurrency (concurrency)

Axios.all (iterable)//all function executes all requests

Axios.spread (callback)//processing response back callback function

Code: Getall:function () {
function Getbooks () {return axios.get (' api/books '); }
function Getreaders () {return axios.get (' api/readers '); }
Axios.all ([Getbooks (), Getreaders ()]). Then (
Axios.spread (function (books, readers) {
When all two requests are complete, the function is called, the first parameter is the result of the first request, and the second is the result of the second request
Console.log (Books.data);
Console.log (Readers.data);
})
);
}

4. Create an instance, instance method

To create a new instance
Axios.create ([config])
Instance method
Some instance methods are listed below. The specific settings will be merged in the instance settings.
Axios#request (config)
Axios#get (Url[,config])
Axios#delete (Url[,config])
Axios#head (Url[,config])
Axios#post (Url[,data[,config]])
Axios#put (Url[,data[,config]])

Axios#patch (Url[,data[,config]])


Code:

1. Create Axios Instance
var instance = axios.create ({
Method: ' Get ',
URL: ' Api/goodslists ',
params:{"Goodsid": "01002"}
});
2, send the request
Instance.request ()
. Then (function (response) {
Console.log (Response.data);
Vueobj.goodslist = Response.data;
})
. catch (function (error) {
Console.log (Error);
});


5. Axios Request configuration and Response data format 1), requested configuration

' URL ' is a server link that is used to request
URL: '/user ',
' method ' is the request approach when initiating a request
Method: ' Get ',
' BaseURL ' if ' url ' is not an absolute address, it will be added to the front.
This setting is handy when Axios uses relative addresses
The method in its instance
BaseURL: ' http://some-domain.com/api/',
' Transformrequest ' allows the requested data to be transformed before it is uploaded to the server.
This applies only to ' put ', ' get ', ' PATCH ' method.
The last function in the array must return a string, a ' arraybuffer ', or ' Stream '
Transformrequest:[function (data) {
Processing request data According to your own needs
return data;
}],
' Transformresponse ' allows the returned data to be processed before it is passed into the Then/catch
Transformresponse:[function (data) {
Processing data as needed
return data;
}],
' Headers ' is a custom header message to be sent
headers:{' x-requested-with ': ' XMLHttpRequest '},
' Params ' is a request parameter in a request connection, must be a pure object, or a 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 a request for the required settings
Apply only to ' put ', ' POST ', ' PATCH ', request method
When ' transformrequest ' is not set, it must be of one of the following types (not repeatable.) ):
-string,plain Object,arraybuffer,arraybufferview,urlsearchparams
-Browser only: Formdata,file,blob
-Node:stream only
data:{
FirstName: ' Fred '
},
' Timeout ' defines the time of the request, in milliseconds.
If the requested time exceeds this set time, the request will stop.
timeout:1000,

' Withcredentials ' indicates whether Cross-domain requests,
should be using a certificate
Withcredentials:false//Default value


' Adapter ' adapters that allow custom processing requests, which makes testing simpler.
Returns a promise and provides validation returns (view [response docs] (#response-api)
Adapter:function (config) {
/*...*/
},


' Xsrfheadername ' is the name of the HTTP header (header), and the header carries the XSRF value
Xrsfheadername: ' X-xsrf-token ',//default value


' Onuploadprogress ' allows handling of events in the upload process
Onuploadprogress:function (progressevent) {
What you want to do when a local process event occurs
},


' Ondownloadprogress ' allows events to be processed by the download process
Ondownloadprogress:function (progressevent) {
What you want to do in the download process
},


' Maxcontentlength ' defines the maximum capacity of the HTTP return content
maxcontentlength:2000,


' Validatestatus ' defines promise's resolve and reject.
The HTTP return status code, if ' Validatestatus ' returns True (or is set to null/undefined), the promise will accept, and the other promise will reject it.
Validatestatus:function (status) {
Return status >= && stauts < 300;//default
},
' Httpagent ' and ' httpsagent ' Define a custom proxy when an HTTP or HTTPS request is generated, in Nodejs.
This allows you to set some options, like ' keepAlive '-which is not open by default.
Httpagent:new http. Agent ({Keepalive:treu}),
Httpsagent:new HTTPS. Agent ({keepalive:true}),


' Proxy ' defines the server's host name and port number.
' auth ' indicates that HTTP Basic authentication should be connected to ' proxy ' and provide a certificate.
This will set a ' Proxy-authorization ' header (header) to overwrite 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 a request
(See the detailed section of the cancellation below)
Canceltoke:new Canceltoken (function (cancel) {
})
}


2), the format of the response data:

{
' Data ' is the reply provided by the server (relative to the request)
data{},


' status ' is the HTTP status code returned by the server
STATUS:200,




' StatusText ' is the HTTP status information returned by the server
StatusText: ' OK ',


' Headers ' is the headers that is carried in the server return
headers:{},


' Config ' is a setting for Axios, for the purpose of requesting (request)
config:{}

}

Using then, you will receive the following information


Axios.get ('/user/12345 ')
. Then (function (response) {
Console.log (Response.data);
Console.log (Response.Status);
Console.log (Response.statustext);
Console.log (response.headers);
Console.log (Response.config);
});
When using catch, or passing in a reject callback as the second parameter of then, the returned error message can be used.
6.Axios Interceptor.

You can intercept them before requesting or returning to be then or catch handling.


1), Request interceptor
Axios.interceptors.request.use (
Function (config) {//config parameter is the requested configuration
Config.url= ' api/goodslists '; modify the URL of the request before sending the request
return config
},
Function (Error) {
Console.log (' request failed ')
return Promise.reject (Error)
}
);

2), Response interceptor

Axios.interceptors.response.use (
Function (response) {//response parameter is a response object
Response.data.unshift ({"Goodsid": "Item Number", "goodsname": "Commodity Name", "Goodsprice": "Commodity Price"});//Add an object to the response data
return response;
}, function (Error) {
Console.log (' response error ')
return Promise.reject (Error)

})

3), the requested code:
Let vueobj = this;
Axios.request ({
Method: ' Get ',
URL: ' Api/readers ',
params:{
"Goodsid": "01002"
}
})
. Then (function (response) {
Console.log (Response.data);
Vueobj.goodslist = Response.data;
})
. catch (function (error) {
Console.log (Error);
}); the difference between 7.ajax,jquery Ajax,axios and fetch

Ajax:
Ajax Nature Needless to say, the earliest appearance of the Send back-end request technology, subordinate to the original JS, the core use of XMLHttpRequest objects, multiple requests if there is a succession of relations, there will be a callback to hell.
Jquery Ajax:
It is the send back-end request technology in the jquery framework, because jquery is based on the original encapsulation, so jquery Ajax is naturally also the original AJAX encapsulation
Fetch:
The fetch is a substitute for Ajax, which appears in ES6 and uses the Promise object in ES6. The fetch is based on promise design. The code structure of the fetch is much simpler than Ajax, and the parameters are a bit like jquery Ajax. However, be sure to remember that the fetch is not a further encapsulation of Ajax, but a native JS. The FETCH function is native JS and does not use the XMLHttpRequest object.
Axios

Axios is not native JS, need to install, it can be used on the client, can also be used on the Nodejs end. Axios can also be intercepted in the request and response phases. is also based on the Promise object. The concept of specific reference Axios


Thanks, come on.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.