can#39;t get response status code with JavaScript fetch(无法使用 JavaScript 获取响应状态代码)
问题描述
我正在尝试创建一个登录表单.当我用 Postman 测试服务时,我会得到一个带有状态码等的 body 对象.
I'm trying to create a login form. when I'm testing the service with Postman, I will get a body object with status code and etc.
但是,使用 JavaScript 获取,我无法获取 body 对象,我刚刚收到一个错误:
But, with JavaScript fetch, I can't get body object and I just received an error:
export const login = (username,password) => {
return dispatch=>{
const basicAuth = 'Basic ' + btoa(username + ':' + password);
let myHeaders = new Headers();
myHeaders.append('Authorization', basicAuth);
myHeaders.append('Content-Type', 'application/json');
fetch(`${baseUrl}api/user/login`, {
withCredentials: true,
headers: myHeaders
})
.then(function (response) {
return response.json();
})
.then(function (json) {
dispatch(setLoginInfo(json))
})
.catch(err =>{
console.log(err)
dispatch(loginFailed())
});
}
}
我需要获取状态码.
推荐答案
状态码是 status
属性在响应对象上.此外,除非您在 error 响应中使用 JSON(当然有些人会这样做),否则您需要检查状态代码(或 ok
flag) 在调用 json
之前:
The status code is the status
property on the response object. Also, unless you're using JSON with your error responses (which some people do, of course), you need to check the status code (or the ok
flag) before calling json
:
fetch(`${baseUrl}api/user/login`, {
withCredentials: true,
headers: myHeaders
})
.then(function(response) {
console.log(response.status); // Will show you the status
if (!response.ok) {
throw new Error("HTTP status " + response.status);
}
return response.json();
})
.then(// ...
不检查请求是否成功是一个常见的错误,我 写了它上我贫血的小博客.
Not checking that the request succeeded is such a common mistake I wrote it up on my anemic little blog.
这篇关于无法使用 JavaScript 获取响应状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法使用 JavaScript 获取响应状态代码


基础教程推荐
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01