繁体   English   中英

即使出现400错误请求错误,如何捕获服务器响应?

[英]How to catch the server response, even if 400 bad request error occured?

考虑以下代码。 这只是一个带有axios库的简单http发布请求。

axios.post('http://localhost/users', this.state)
        .then(function(response) {
          if (response.status == 201) {
            browserHistory.push('/features');
          } 
        })
        .catch(function(error) {
          console.log(error);
        })

如果用户向输入输入了错误的数据,则来自服务器的响应保存信息,例如

  • 密码必须比...更长
  • 邮件丢失了@符号
  • 等等...

不幸的是,如果有400 bad request状态,我不知道如何进入该响应。 它只是显示错误,但我无法得到响应。

如果响应状态为201 ,则会正确显示响应。 但是在400情况下,即使我改变条件并添加else if (response.status == 400) { console.log(response) }它也不会显示响应。

任何帮助高度赞赏。

只需查看axios文档,看起来响应应该在错误对象中公开(即console.log(error.response) )。

有关响应代码超出2xx时提供的不同信息的更多信息: https//github.com/mzabriskie/axios#handling-errors

您需要记录响应的数据:

axios.post('http://localhost/users', this.state)
        .then(function(response) {
          browserHistory.push('/features');
        })
        .catch(function(error) {
          console.log(error.response.data); // this is the part you need that catches 400 request
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM