Home Web Front-end HTML Tutorial 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 http status code Obtain

Simple JavaScript Tutorial: How to Get HTTP Status Code

JavaScript Tutorial: How to get HTTP status code, specific code examples are required

Foreword:
In web development, data interaction with the server is often involved scene. 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.

  1. Use the XMLHttpRequest object to obtain the status code

XMLHttpRequest is an HTTP request object, which can be used in JavaScript to interact with the server. The following is a sample code to obtain the HTTP status code:

let xhr = new XMLHttpRequest();

xhr.open('GET', 'http://example.com/api', true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE) {
    if (xhr.status === 200) {
      console.log('请求成功');
    } else {
      console.log('请求失败,状态码为:' + xhr.status);
    }
  }
};

xhr.send();
Copy after login

In the above code, we first create an XMLHttpRequest object, and then use the xhr.open method to specify the request method and address , and then monitor the change of request status through the xhr.onreadystatechange method. When xhr.readyState is XMLHttpRequest.DONE, the request has been completed.

Next, we obtained the HTTP status code returned by the server through xhr.status. If the status code is equal to 200, it means the request was successful; otherwise, it means the request failed.

  1. Use Fetch API to obtain status code

Fetch API is a new feature of JavaScript, which provides a more modern and powerful way to interact with the server. The following is a sample code that uses the Fetch API to obtain the HTTP status code:

fetch('http://example.com/api')
  .then(response => {
    if (response.ok) {
      console.log('请求成功');
    } else {
      console.log('请求失败,状态码为:' + response.status);
    }
  })
  .catch(error => {
    console.log('请求发生错误:', error);
  });
Copy after login

In the above code, we use the fetch function of the Fetch API to initiate a GET request. Then process the server's response result through the .then method. If response.ok is true, it means the request is successful; otherwise, it means the request fails. The HTTP status code can be obtained through response.status.

In addition, we can also use the .catch method to catch errors during the request process.

  1. Other common HTTP status code processing examples

In addition to 200, HTTP status codes have many other values, each value represents a different meaning. Here are some common HTTP status code handling examples:

  • 301 Permanent redirect:
if (xhr.status === 301) {
  console.log('请求被永久重定向');
}
Copy after login
  • 404 Page not found:
if (xhr.status === 404) {
  console.log('请求的页面不存在');
}
Copy after login
  • 500 Server error:
if (xhr.status === 500) {
  console.log('服务器发生错误');
}
Copy after login
  • 503 Service unavailable:
if (xhr.status === 503) {
  console.log('服务当前不可用');
}
Copy after login

Proceed accordingly according to different status codes , can better cope with different error situations.

Conclusion:
This article introduces how to use JavaScript to obtain the HTTP status code and provides some specific code examples. By mastering this knowledge, you will be able to better handle errors during interaction with the server and improve web development efficiency. Hope this article is helpful to you!

The above is the detailed content of Simple JavaScript Tutorial: How to Get HTTP Status Code. 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Revealing the causes of HTTP status code 460 Revealing the causes of HTTP status code 460 Feb 19, 2024 pm 08:30 PM

Decrypting HTTP status code 460: Why does this error occur? Introduction: In daily network use, we often encounter various error prompts, including HTTP status codes. These status codes are a mechanism defined by the HTTP protocol to indicate the processing of a request. Among these status codes, there is a relatively rare error code, namely 460. This article will delve into this error code and explain why this error occurs. Definition of HTTP status code 460: First, we need to understand the basics of HTTP status code

A deep dive into the meaning and usage of HTTP status code 460 A deep dive into the meaning and usage of HTTP status code 460 Feb 18, 2024 pm 08:29 PM

In-depth analysis of the role and application scenarios of HTTP status code 460 HTTP status code is a very important part of web development and is used to indicate the communication status between the client and the server. Among them, HTTP status code 460 is a relatively special status code. This article will deeply analyze its role and application scenarios. Definition of HTTP status code 460 The specific definition of HTTP status code 460 is "ClientClosedRequest", which means that the client closes the request. This status code is mainly used to indicate

Analyze the causes and solutions of HTTP status code 460 Analyze the causes and solutions of HTTP status code 460 Feb 20, 2024 pm 02:03 PM

Explore the causes and solutions of HTTP status code 460. The HTTP status code is a standardized numeric code used by the HTTP protocol to indicate the result returned by a request. In the HTTP/1.1 specification, a total of 5 types of status codes are defined, among which 4xx status codes indicate request errors and 5xx status codes indicate server errors. Among these status codes, we have rarely heard of the 460 status code. So, what is HTTP status code 460? What is the reason for its appearance? How should we solve it? First, let’s look at the HTTP status codes

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

An in-depth analysis of HTTP status code 550: Bad email address An in-depth analysis of HTTP status code 550: Bad email address Feb 18, 2024 pm 01:44 PM

In-depth analysis of HTTP status code 550: Incorrect email address With the rapid development of the Internet, email has become an indispensable part of people's daily life and work. Through email, people can transfer information and communicate quickly and easily. However, in the process of using email, we sometimes encounter some problems, one of which is the wrong email address. When sending emails online, we often encounter situations where the email fails to be sent. When we receive something like “550Error:Invalid

Where to get Google security code Where to get Google security code Mar 30, 2024 am 11:11 AM

Google Authenticator is a tool used to protect the security of user accounts, and its key is important information used to generate dynamic verification codes. If you forget the key of Google Authenticator and can only verify it through the security code, then the editor of this website will bring you a detailed introduction on where to get the Google security code. I hope it can help you. If you want to know more Users please continue reading below! First open the phone settings and enter the settings page. Scroll down the page and find Google. Go to the Google page and click on Google Account. Enter the account page and click View under the verification code. Enter your password or use your fingerprint to verify your identity. Obtain a Google security code and use the security code to verify your Google identity.

Troubleshooting the causes and solutions for HTTP status code 550 Troubleshooting the causes and solutions for HTTP status code 550 Feb 20, 2024 am 09:49 AM

Explore the causes and solutions of HTTP status code 550 Introduction: In network communications, HTTP status codes play an important role and are used to indicate the results of the server processing the request. Among them, HTTP status code 550 is a relatively rare status code that is usually related to the server refusing to execute the request. This article will explore the causes of HTTP status code 550 and provide solutions. 1. The basic concept of HTTP status code. Before understanding the HTTP status code 550, let us first briefly understand the basic concept of HTTP status code.

Analysis of the meaning of HTTP status code 460 Analysis of the meaning of HTTP status code 460 Feb 24, 2024 pm 03:51 PM

Vernacular explanation: What does HTTP status code 460 mean? Hello everyone, today we will talk about a strange number in the HTTP status code - 460. I believe many friends have encountered various error pages when developing websites or browsing the web, including HTTP status codes. As for this 460 status code, you may be curious, what does it mean? First, let’s first understand what HTTP status codes are. During the process of accessing web pages or interacting with the server, the client

See all articles