Nuxt Axios模块读取状态码

4

我正在调用一个返回至少2个成功状态码的Rest API。 一个是正常的200 OK,另一个是202 Accepted状态码。 两者都在body中返回内容。 如果我在Postman中执行我的调用,可能会得到以下结果:

状态码:202 Accepted。带有“Queued”或其他值的Body enter image description here enter image description here 或者

状态码:200 OK。带有“ValueOfSomeToken”的Body enter image description here 使用axios在我的nuxt应用程序中进行调用:

this.$axios.$get('/Controller/?id=1')
  .then((response)=>{
     if(response=='Queued'){
         //Do something
     }
     else if (response=='Expired'){
       //Do something
     }
     else{
       //Do something
     }
  })
  .catch((error)=>{
            console.log(error);
  });

...成功了,但我实际上想获取状态码(因为202有其他值的响应体)。

我不知道如何读取状态码。

我尝试使用(response, code) => ... 但是code没有任何值。

2个回答

13

您可以使用非 $ 前缀的函数,如 this.$axios.get(),而不是 this.$axios.$get() 来获取完整的响应。

// Normal usage with axios
let { data } = await $axios.get('...'));

// Fetch Style
let data = await $axios.$get('...');

(来源)


6
你可以从axios的响应对象中提取状态码
如果你打印响应对象(如下图所示),你可以看到响应对象中所有的对象。其中之一是状态对象

enter image description here

response.status会给你发送自服务器的状态码。

axios.get("http://localhost:3000/testing").then((response)=>{
    console.log("response ",response);
    if(response.status == 200){
        //do something
    }
    else if(response.status == 202){
        //do something
    }
    else if(response.status == 301){
        //do something
    }
}).catch((err)=>{
    console.log("err11 ",err);
})

在服务器端,您可以使用res.status()方法显式发送任何状态码,有关详细信息,请参阅this documentation
app.get('/testing',(req, res)=> {
  res.status(202).send({"res" : "hi"});
});

更新:

默认情况下,@nuxtjs/axios.then((response)) 中返回 response.data

$axios.onResponse 事件将有完整的响应对象访问权限。

你需要设置拦截器来拦截 $axios.onResponse 事件并修改响应对象。

在插件目录下创建一个插件,plugin/axios.js

nuxt.config.js 中更新 plugins 部分:plugins : ['~/plugins/axios']

export default function ({ $axios, redirect }) {
    $axios.onResponse(res=>{
        console.log("onResponse ", res);
        res.data.status = res.status;        
        return res;
    })
}

在这个拦截器中的res对象中,您将拥有所有值(如我第一张截图中所示)。但是这个res对象不会被原样返回,只有res.data被返回到我们的程序中。
我们可以更新res.data中的内容,然后像我的程序中一样返回res对象res.data.status = res.status;
现在,当axios返回res.data时,我们将可以在.then((response)) promise中的response对象中访问res.data.status值。
您可以在this.$axios中使用response.status访问状态。
this.$axios.$get("url").then((response) =>{
    console.log("status ",response.status);
}).catch((err) => {
    console.log("res err ",err);
});

谢谢您的回答。但是正如我所说,我想使用NUXT.js axios模块,而不是作为单独的包。我知道使用axios可以解决问题。我想知道为什么在axios nuxt模块上无法工作。即使在postman中,我也能看到正确的状态返回。我的响应只有字符串...没有数据对象或状态/状态文本。 - CodeHacker
@CodeHacker,我已经更新了答案,并加入了@nuxtjs/axios模块的详细信息。如果有帮助,请告诉我。 - divine
1
那就是我一直在寻找的答案。非常好用! - CodeHacker
@divine 感谢您的详细解释,但是我无法使用任何事件处理程序(onError、onResponse...)。我总是会收到“$axios.onResponse不是函数”的错误。有什么想法吗? - Anonymous
@Anonymous 可能是配置问题。你能在 Github 上分享你的代码吗? - divine
非常好!谢谢! - Samuel Cesc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接