[英]Getting axios response if Node server sends status 400
Simple Node.js get a route that either sends a response status of 200 or 400 in a try-catch block. 简单的Node.js获得的路由在try-catch块中发送了200或400的响应状态。
If the server sends the 200 response, I can log that in my Axios get request (console.log(response.status)). 如果服务器发送200响应,则可以将其记录在我的Axios get请求(console.log(response.status))中。
However, if the catch block runs and sends a status of 400, I just get the error in the browser displaying the error, and my response.status does not run. 但是,如果catch块运行并发送状态为400,我只会在浏览器中看到显示错误的错误,并且我的response.status无法运行。 Why is this?
为什么是这样?
I want to render a message in my front end with react depending on the status that is being sent back. 我想在前端使用响应状态发送消息,具体取决于发送回的状态。 If code 400 is sent, then I want to retrieve that from the response in my frontend, but at the moment, it does not reach that.
如果发送了代码400,那么我想从前端的响应中检索该代码,但目前还没有达到。
Am I missing something about how these Node.js status codes work? 我是否缺少有关这些Node.js状态代码如何工作的信息?
Thank you for your time 感谢您的时间
Here is the Node.js route 这是Node.js路线
try {
const user = req.user;
res.status( 200 ).send();
} catch ( e ) {
res.status( 400 ).send();
}
And here is the Axios get request 这是Axios获取请求
useEffect( () => {
const call = async () => {
let response = await axios( {
method: "get",
url: "/tasks"
} );
console.log( response );
if ( response.status === 200 ) {
setAuthorized( true );
console.log( "We are authorized" );
} else {
setAuthorized( false );
console.log( "We are not authorized" );
}
};
call();
} );
The problem is that axios sees a 400 status as an error, and will do a throw. 问题是axios将400状态视为错误,并且会抛出异常。 You can pass a parameter to axios to prevent this, and just pass it back.
您可以将参数传递给axios以防止这种情况,然后将其传递回来。
Here is an example of how to do it using a validateStatus
hook: 这是一个如何使用
validateStatus
挂钩的示例:
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})
For more information see "Handling errors" in https://github.com/axios/axios 有关更多信息,请参见https://github.com/axios/axios中的 “处理错误”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.