在 JavaScript 中获取获取 HTTP 响应的状态代码

获取获取 HTTP 响应的状态代码

Get the Status Code of a Fetch HTTP Response in JavaScript

访问对象status的属性response以获取使用该方法发出的 HTTP 请求的状态代码fetch

response.status属性包含响应的 HTTP 状态代码,例如200成功响应或500服务器错误。

索引.js
async function makeRequest() { try { const response = await fetch('https://randomuser.me/api/'); console.log('response.status: ', response.status); // 👉️ 200 console.log(response); } catch (err) { console.log(err); } } makeRequest();

我们等待调用fetch方法的响应
并将结果分配给一个
response变量。

要获取 HTTP 响应的状态代码,请访问
对象的
状态
属性
response

使用 Promise.then() 而不是 async/await

Here is an example that uses .then() and .catch() instead of async/await.

index.js
function makeRequest() { fetch('https://randomuser.me/api/') .then(response => { console.log('response.status: ', response.status); // 👉️ 200 console.log(response); }) .catch(err => { console.log(err); }); } makeRequest();

The status property on the response object will only be populated for HTTP
responses.

If the server doesn’t respond at all, you encounter a CORS error or misspell the
URL, you will get a network error.

The network error would run the catch() function and the status property
would not be populated as it isn’t a server HTTP response.

# A complete example of handling error when using fetch

Here is a complete example of handling requests and errors using fetch.

index.js
async function makeRequest() { try { const response = await fetch('https://randomuser.me/api/'); console.log('status code: ', response.status); // 👉️ 200 if (!response.ok) { console.log(response); throw new Error(`Error! status: ${response.status}`); } const result = await response.json(); return result; } catch (err) { console.log(err); } } makeRequest();

We used the
response.ok
property to check if the server responded with a status in the range of
200-299.

If the server’s HTTP response was successful (200-299), the response.ok property will have a value of true, otherwise, it’s value will be false.

Fetch doesn’t reject the promise response for HTTP requests on its own, so we
have to check if the ok property was set to false.

If the ok property is set to false, the request wasn’t successful and we
have to throw an error on our own.

If there is a network error, e.g. a CORS error, or an error related to creating
the HTTP request, the promise would get rejected automatically and our catch
block would get triggered.

As previously noted, if there is a network error, the status property will not
be populated as the error didn’t come from a server HTTP response.

I’ve also written an article on
how to get the status code of an Axios HTTP error.

# Additional Resources

You can learn more about the related topics by checking out the following
tutorials: