获取获取 HTTP 响应的状态代码
Get the Status Code of a Fetch HTTP Response in JavaScript
访问对象status
的属性response
以获取使用该方法发出的 HTTP 请求的状态代码fetch
。
该response.status
属性包含响应的 HTTP 状态代码,例如200
成功响应或500
服务器错误。
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
.
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
.
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
.
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:
- ReferenceError: fetch is not defined in NodeJs
- TypeError: Failed to fetch and CORS in JavaScript [Solved]
- Fetch API cannot load localhost. URL scheme is not supported
- fetch() returns empty Response Body in JavaScript [Solved]
- How to get the MIME type of a File in JavaScript & Node.js
- Chrome: How to Copy an Object or Array from the Console tab