Home > Web Front-end > HTML Tutorial > Master practical skills for obtaining HTTP status codes in JavaScript

Master practical skills for obtaining HTTP status codes in JavaScript

王林
Release: 2024-01-05 10:38:59
Original
1366 people have browsed it

Master practical skills for obtaining HTTP status codes in JavaScript

Practical tips: Master the method of obtaining HTTP status code in JavaScript, you need specific code examples

Introduction:
In web development, you often need to interact with the backend Perform data interaction. In this process, it is very important to understand the HTTP status code, which can help us determine whether the request is successful and handle error conditions. This article will introduce how to obtain the HTTP status code through JavaScript, and provide specific code examples to help readers quickly master this technique.

1. Use the XMLHttpRequest object to obtain the HTTP status code
XMLHttpRequest is an object used for asynchronous communication between the client and the server. In JavaScript, we can use the XMLHttpRequest object to send HTTP requests and obtain the corresponding status code.

Code example:

let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.example.com/data', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) { // 请求完成
    let status = xhr.status;
    console.log('HTTP状态码:', status);
  }
}
xhr.send();
Copy after login

Analysis:
First, we create an XMLHttpRequest object instance xhr. Then, use the xhr.open() method to specify the type of request (GET, POST, etc.) and the requested URL. The third parameter is the asynchronous identifier. Setting it to true means sending the request asynchronously.

Next, we bind a callback function to the onreadystatechange event of the xhr object. This callback function will be triggered when the state of the xhr object changes. When the onreadystatechange event is triggered, we first determine whether the readyState of the xhr object is 4, which means that the request has been completed and the response has been received.

Finally, we get the HTTP status code through the xhr.status attribute and print it out on the console.

2. Use fetch API to obtain HTTP status code
fetch API is a modern network request API based on Promise, which provides a more concise and flexible way to communicate over the network. Through the fetch API, we can also easily obtain the HTTP status code.

Code example:

fetch('http://api.example.com/data')
  .then(response => {
    let status = response.status;
    console.log('HTTP状态码:', status);
  })
  .catch(error => {
    console.log('请求发生错误:', error);
  });
Copy after login

Analysis:
First, we use the fetch function to send a GET request and pass in the requested URL as a parameter. The fetch function returns a Promise object.

Next, we use the then method of the Promise object to define a callback function. When the request returns, the callback function will be triggered and accept a response object as a parameter.

In the callback function, we obtain the HTTP status code through the response.status attribute and print it out on the console.

If an error occurs in the request, we can capture the error through the catch method and print out the error information on the console.

3. Use axios library to obtain HTTP status code
axios is a Promise-based HTTP client that can be used in browsers and Node.js. It provides a convenient API for sending HTTP requests and processing responses.

Code example:

axios.get('http://api.example.com/data')
  .then(response => {
    let status = response.status;
    console.log('HTTP状态码:', status);
  })
  .catch(error => {
    console.log('请求发生错误:', error);
  });
Copy after login

Analysis:
First, we use the get method of axios to send a GET request and pass in the requested URL as a parameter. The get method returns a Promise object.

Next, we use the then method of the Promise object to define a callback function. When the request returns, the callback function will be triggered and accept a response object as a parameter.

In the callback function, we obtain the HTTP status code through the response.status attribute and print it out on the console.

If an error occurs in the request, we can capture the error through the catch method and print out the error information on the console.

Conclusion:
This article introduces three common methods to obtain HTTP status codes: using XMLHttpRequest object, fetch API and axios library. By mastering these methods and being able to use them flexibly, we can more accurately determine the request status and handle error situations, improving the efficiency and quality of web development. Hope this article can be helpful to readers.

Reference:

  1. MDN Web Docs: XMLHttpRequest - https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
  2. MDN Web Docs: Fetch API - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
  3. Axios - https://axios-http.com/

The above is the detailed content of Master practical skills for obtaining HTTP status codes in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template