Javascript 如何捕获服务器响应,即使出现400个错误请求?
考虑以下代码。这只是一个带有Javascript 如何捕获服务器响应,即使出现400个错误请求?,javascript,promise,Javascript,Promise,考虑以下代码。这只是一个带有axios库的简单http post请求 axios.post('http://localhost/users', this.state) .then(function(response) { if (response.status == 201) { browserHistory.push('/features'); } }) .catch(functi
axios
库的简单http post请求
axios.post('http://localhost/users', this.state)
.then(function(response) {
if (response.status == 201) {
browserHistory.push('/features');
}
})
.catch(function(error) {
console.log(error);
})
如果用户在输入中输入了错误的数据,服务器的响应将保留信息,例如
- 密码必须比
- 邮件缺少
标志@
- 等等
400错误请求
状态,我不知道如何进入该响应。它只是显示了错误,但我无法得到响应
如果响应状态为201
,则正确显示响应。但是在400
的情况下,即使我更改了条件并添加了else,如果(response.status==400){console.log(response)}
它也不会显示响应
非常感谢您的帮助。只要看看axios文档,响应似乎应该显示在错误对象中(即
console.log(error.response)
)
有关响应代码超出2xx时提供的不同信息的更多信息,请参见此处:您需要记录响应数据:
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
});
代码是否符合
.catch
的要求?保存了我的一天:D