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

Jan 05, 2024 am 10:38 AM
javascript status code Get http

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Introduction to HTTP 525 status code: explore its definition and application Introduction to HTTP 525 status code: explore its definition and application Feb 18, 2024 pm 10:12 PM

Introduction to HTTP 525 status code: Understand its definition and usage HTTP (HypertextTransferProtocol) 525 status code means that an error occurred on the server during the SSL handshake, resulting in the inability to establish a secure connection. The server returns this status code when an error occurs during the Transport Layer Security (TLS) handshake. This status code falls into the server error category and usually indicates a server configuration or setup problem. When the client tries to connect to the server via HTTPS, the server has no

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles