javascript - 无法使用 JavaScript 获取响应状态代码
问题描述
我正在尝试创建一个登录表单。当我用 Postman 测试服务时,我会得到一个带有状态码等的 body 对象。
但是,使用 JavaScript 提取,我无法获取 body 对象,我刚刚收到一个错误:
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
响应对象的属性。此外,除非您在错误响应中使用 JSON(当然有些人会这样做),否则您需要在调用之前检查状态代码(或ok
标志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(// ...
不检查请求是否成功是一个常见的错误,我把它写在我贫血的小博客上。
推荐阅读
- lambda - 为什么我会得到
. 在 0x000001EFDE355310> - apache - 如何使用apache mod_rewrite从请求的URL中的文件名中删除md5而不使用md5?
- node.js - 在 Windows 上启动 Nodejs 应用程序在启动时使用 taskscheduler 无法正常工作
- jestjs - TypeError:开玩笑:转换必须导出某些东西
- ruby-on-rails-5 - 使用 ActiveStorage 在我的开发环境中未显示图像
- discord.js - 如何使用提及的所有频道和角色进行嵌入
- jquery - 如何使用循环为不同的用户但相同的类名 div 附加不同的数据?
- linux - 无法安装 wine 以在 ubuntu 中运行 emu8086
- r - 新 R 版本的问题
- r - HI 尝试解决以下循环功能并运行现在获取未找到对象的错误数据图片