首页 > 解决方案 > 使用 Axios 存储 cookie 连接

问题描述

我想用axios访问一个api的信息,问题是axios无法获取数据。我已经用 Postman 测试过,我可以很好地访问数据。我还注意到 Posteman 存储了一个登录 cookie,我试图用 Axios 重现,但我不能。

我看到axios.defaults.withCredentials = true必须使用它,但它不起作用,也许我做错了。

这是我的代码:

getData() {
       axios.defaults.withCredentials = true;
       let url = "***"
       axios
           .get(url)
           .then(response => {
               this.name = response
           }).catch((error) => {
               this.name = error;
           })
   }

先感谢您!

标签: javascriptaxios

解决方案


如果您自己没有设置邮递员 cookie,那么它就是邮递员的东西,因此它可能对您的 axios 请求没有用处

小心,axios 返回的数据就像{"headers": stuff, "data": yourdata}Postman 只显示“数据”键中的数据一样

所以你可能想做

getData() {
       let url = "***"
       axios
           .get(url)
           .then(response => {
               this.name = response.data
           }).catch((error) => {
               this.name = error;
           })
   }

否则,您可以将您的 Postman 请求导出到代码,这样您就可以看到 Postman 发送到 API 的内容(使用 Postman 中的“保存”按钮下的“代码”按钮)


推荐阅读