This is the 15th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
preface
In the last few articles, we’ve looked at documenting JavaScript in the browser, as well as summarizing other topics.
After learning about the FETCH network request method in the introduction, this article continues to learn about other details about the network: HTTP status codes
Fetch () request processing
You learned in the previous section that a fetch initiates a request and returns a promise. Here the returned response object is judged:
The fetch() of JavaScript in the browser requests the server, returns the response content, and then processes the response content to determine the status code. If it succeeds, the data data is processed, and then the data is parsed for page display
If there is a problem with a failed request, the error is caught and printed: the code is as follows
// Fetch initiates a request
fetch('https://your.site.com/api/user/center/current')
.then(res= > {
// First check the success code and expected type of the response object
if(res.status && res.headers.get("Content-Type") = = ="application/json") { // Determine the return status and result
return res.join() // Returns the period containing the response body
} else {
throw new Error( // Otherwise an error is thrown
`Unexpected response status`
)
}
})
.then(currentUser= > { // When response.json() returns the date obtained here after processing
displayUserInfo(currentUser) // Get it and parse it
})
.catch(err= > { // Or catch an error. What's the problem? Print it out
Fetch () itself rejects the date if the browser user is offline
// If the server returns an unexpected content response. An error is thrown on it
console.log("Error fetch current user: ", err)
})
Copy the code
Fetch () returns a date resolved into a Response object.
The status property in this object is the HTTP response code, also known as the status code. If I succeed, I’ll write it as 200
NOT FOUND 404… And so on.
For the HTTP request code, continue to update in the next section..
Read more about it
- -number – This is a function
- Automatic type conversion
- Infix operators in JavaScript
- Do you know what JavaScript Typeof is?
- Learn a few representative events in JavaScript
- Learn to Understand client-side JavaScript- Event Classification (part 1)
- Client-side JavaScript- Event Classification (2)
- Learn to understand JavaScript events and event loops
- Understand JavaScript in the browser – event registration
- The javascript-fetch () network request method in the browser
- JavaScript-fetch() in browser
Calm Down & Carry On!
Buy Less by Know More! Come on!
Learning, recording and accumulating is a long process!
Refer to the content
| MDN network request