Nuxt Axios 模块读取状态码

Nuxt Axios Module read status code

我正在呼叫 API 至少有 2 个成功状态代码的 return。 正常的 200 OK 和 202 Accepted 状态代码。 两者都return一个内容在body。 如果我在邮递员中执行我的电话,我可能会得到类似

状态代码:202 已接受。使用 Body "Queued" 或其他一些值

状态码:200 正常。随着 Body "ValueOfSomeToken" 在我的 nuxt 应用程序中使用 axios 进行调用:

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 对于 body 响应有其他值)

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

我尝试使用 (response,code) =>... 但是代码什么都不是。

您可以从 axios

中的响应对象中提取 status codes

如果您打印响应对象(如下图所示),您可以看到响应对象中的所有对象。其中之一是 status object

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 returns response.data.then((response))

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

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

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

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

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

在此拦截器的 res object 中,您将拥有所有值(如我的第一个屏幕截图所示)。但是这个 res object 并没有按原样 returned,只有 res.data 被 returned 到我们的程序。

我们可以更新 res.data 中的内容,然后 return res object ,如我的程序 res.data.status = res.status; 所示。

现在 axios return 时 res.data 我们将可以访问 response 对象中的 res.data.status.then((response)) promise

您可以在 this.$axios

中使用 response.status 访问状态
this.$axios.$get("url").then((response) =>{
    console.log("status ",response.status);
}).catch((err) => {
    console.log("res err ",err);
});

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

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

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

(source)