HTTP status code acquisition method in JavaScript
Introduction:
In front-end development, we often need to handle the interaction with the back-end interface, and HTTP Status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples.
1. What is HTTP status code
HTTP status code refers to the numeric code contained in the response header returned by the server when the browser initiates a request to the server. This numeric code represents the result of the server's processing of the request. Common status codes include 200, 404, 500, etc.
2. Using XMLHttpRequest
XMLHttpRequest is a built-in browser object used to interact with the server, through which we can send HTTP requests and get the server's response. When getting the server response, we can get the HTTP status code through the status attribute of the XMLHttpRequest object.
Specific code example:
var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://example.com/api'); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE) { var status = xhr.status; console.log(status); } }; xhr.send();
Through the above code, we sent a GET request to the "http://example.com/api" interface, and obtained the HTTP status code.
3. Use fetch
fetch is a simplified network request API in JavaScript. It uses Promise to handle asynchronous operations of network requests. The result returned by fetch is a Promise object, and we can obtain the HTTP status code through its res.status attribute.
Specific code example:
fetch('http://example.com/api') .then(function(res) { var status = res.status; console.log(status); });
Through the above code, we also sent a GET request to the "http://example.com/api" interface and obtained it after receiving the server response HTTP status code.
The above are two common methods of using JavaScript to obtain HTTP status codes, and specific code examples are provided. In front-end development, understanding and obtaining HTTP status codes can help us better process the data returned by the interface to improve user experience and application reliability. Hope this article is helpful to everyone!
The above is the detailed content of How to get HTTP status code in JavaScript the easy way. For more information, please follow other related articles on the PHP Chinese website!