ali*_*ian 3 javascript http-status-codes fetch reactjs postman
我正在尝试创建一个登录表单。当我用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())
});
}
}
Run Code Online (Sandbox Code Playgroud)
我需要获取状态代码。
Pan*_*her 10
存在status于response对象中。你可以把它放在你的第一个 then 块中
.then(function (response) {
console.log(response.status);
return response.json();
})
Run Code Online (Sandbox Code Playgroud)
由于您正在返回response.json(),因此后续的then并且catch仅得到的结果response.json()是响应的正文。
状态码是status响应对象上的属性。另外,除非您将JSON与错误响应一起使用(当然有人会这样做),否则您需要在调用之前检查状态代码(或okflag)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(// ...
Run Code Online (Sandbox Code Playgroud)
我经常在我贫乏的小博客上写出来的错误就是不能检查请求是否成功。
| 归档时间: |
|
| 查看次数: |
5895 次 |
| 最近记录: |