无法通过JavaScript获取获取响应状态代码

编程入门 行业动态 更新时间:2024-10-26 11:27:23
本文介绍了无法通过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提取,我无法获取主体对象,而我刚收到一个错误:

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()) }); } }

我需要获取状态代码.

推荐答案

状态代码为状态 属性.另外,除非您将JSON与 error 响应一起使用(当然有些人会这样做),否则您需要检查状态代码(或 ok 标志),然后再调用 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获取获取响应状态代码

本文发布于:2023-11-26 01:54:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632179.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:状态   代码   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!