如何在axios中将无效数据输出为404

How to output invalid data as 404 in axios

我正在使用 vue + axios 发出请求。通常是这样的:

axios.get('/url').then(response => {} ).catch(error => {})

如果 HTTP 响应不是 404,这将捕获响应,但如果是 404,它将在捕获中被捕获。

但有时我希望将响应视为错误。例如,如果 GET /user 响应 200 OK,但数据中没有用户,我如何将该响应传输到 catch 块中?

是否可以使用 axios 来做到这一点,还是仅 return response/error 基于 HTTP 状态代码?

这应该发生在您的服务器上。如果没有用户,处理请求的服务器应该 return 404 响应错误。

您可以抛出一个错误,让 catch 块处理您的答案:

axios.get('/url').then(response => {
    if (/* you're not satisfied with the response*/) {
         throw new Error("I'm not satisfied");
    }
}).catch(error => {})

您始终可以使用在 JavaScript 中您可以使用函数共享行为的事实。

function handleError (error) { ... };

axios.get('/url').then(response => { 
    if( "some condition" ) {
       handleError("Some unmet condition");
    }  
).catch(handleError);