Once we were so young. But goose, time flies, time flies, a generation of new people for old people. We’re in our early thirties, and we’ve become big brothers among programmers.
The World of the Internet is fast changing and the latest technology is constantly emerging. Vue, Axios, React, Redux, Angular… And so on and so on. Fortunately, the bottom is the same. So, today we’re going to talk about the bottom line.
When it comes to AJAX, most programmers instinctively think of XMLHttpRequest. Yes, XHR(minions) have been with us for many years. But the minions were born in the early days of the Internet.
Browsers come and go, and there is no single Web standard. So today, the design of the minions looks confusing. JQuery, which we used at one time (and which is a big brother), helps us wrap properly. Solved our use of the trouble. To use jQuery, however, we have to introduce a large file, which is not very friendly for those of us who just want to use jQuery to send Ajax.
As a result, the browser has followed the trend and added a new native method: FETCH
Fetch is another native way for browsers to support AJAX (non-XMLHttprequest). Provides a more reasonable and easier way to get data asynchronously. It’s based on Promise, so for those of you who don’t know Promise, check out the documentation
Send a GET request
2.1 send
To send a request, it’s very simple: the simplest way to send a request
fetch('/api/getMessage')
Copy the code
Take a look at the Network panel:
Request successful!
Check the details
Send the request, done!
Everything is so simple……
2.2 Receiving Data
Received data:
fetch('/api/getMessage')
.then(res= > res.json())
.then(data= > console.log(data))
Copy the code
The result of calling fetch is an instance of Promise. So you can call the then method for state monitoring.
He is very good. He is very good.
The processing here is also divided into two parts:
Decide the format to return for the first time (first brush…)
The second is the actual received data (the second…).
In the first then function, we return a res.json() via return.
What this code means is to process the returned data into JSON format
Return is required because the result of res.json() is still a Promise instance.
In the second THEN function, we can get the result after the processing of the previous THEN function.
Note that there are many methods that can be called in the first then, such as res.text(), res.blob(), etc
Send a POST request
3.1 Sending a Request
The POST request is sent similarly to the GET request, but with an additional configuration parameter
fetch('/api/postMessage', {
method: 'post'
})
Copy the code
The first parameter still represents the URL
The second argument is an object
Configure its Method property to send a POST request.
The network panel:
Request first line information:
3.2 Receiving Data
Again, we process and receive data through the twice-then method
fetch('/api/postMessage', {
method: 'post'
})
.then(function (res) {
return res.json()
})
.then(function (data) {
console.log(data)
})
Copy the code
Return content:
So far we have learned how to send basic GET and POST requests via FETCH. Next, we will go deeper to master more fetch usage methods
4. Carry data
When sending a request, sometimes we need to carry some data with us
This data can be placed in different places depending on the type of request.
- The data for the GET request is placed in the QueryString section of the URL
- The data for the POST request is carried in the request body
4.1 A GET Request Carries data
The simplest way to do this is to place the query string on the URL while concatenating the string.
fetch('/api/getMessage? a=1&b=2&c=3')
Copy the code
It will be carried on it when requested.
But this approach would force us to concatenate strings when sending requests. If there are many fields, it will be a very troublesome thing.
This can be done through URLSearchParams
4.2 URLSearchParams
This is a constructor for the Search part of the URL argument. Simply put, it generates a query string.
Grammar:
var query = new URLSearchParams([init]);
Copy the code
Parameter init(optional):
- string
- 2 d array
- Object (recommended)
String:
var search = '? a=1&b=2&c=3';
var querystring = new URLSearchParams(search);
var str = querystring.toString();
console.log(str)
Copy the code
Output:
Two-dimensional arrays:
var arr = [
['a'.1],
['b'.2],
['c'.3],
['d'.4],
['e'.5]]var querystring = new URLSearchParams(arr);
var str = querystring.toString();
console.log(str)
Copy the code
Output:
Now you can use URLSearchParams to get the parameters, which allows you to quickly generate query strings
4.2 POST Requests Carry Data
The data for the POST request is carried in the request body. We need to set the body property for the second parameter of the fetch.
The body attribute value can be of any of the following types: We will only demonstrate the string case here
- ArrayBuffer
- ArrayBufferView (Uint8Array, etc.)
- Blob/File
- string
- URLSearchParams
- FormData
The body value is a string
fetch("/api/postMessage", {
method: 'post'.body: JSON.stringify({
a: 1.b: 2.c: 3
}),
headers: {
"content-type": 'application/json'}})Copy the code
Request body content:
So far, we have discussed sending and carrying data through the FETCH function for GET and POST requests.
Fetch is a native browser method.
No more writing XHR requests or relying on jQuery.
Please correct any omissions.