【问题标题】:Using cookies with axios and Vue在 axios 和 Vue 中使用 cookie
【发布时间】:2019-06-12 07:42:58
【问题描述】:

我创建了一个使用“jsforce”提供的 SOAP 接口连接到 Salesforce.com 的 Node.js express 服务器。它通过“express-session”包使用会话 cookie 进行授权。到目前为止,它有一个用于登录的 POST 方法和一个用于执行简单查询的 GET。使用 Postman 进行的测试证明该服务器按预期工作。

作为该服务器的浏览器接口,我编写了一个使用 axios 执行 GET 和 POST 的 Vue 应用程序。我需要保存在登录 POST 期间创建的会话 cookie,然后将 cookie 附加到后续的 CRUD 操作中。

我尝试了各种方法来处理 cookie。我尝试过的一种方法是在 POST 上使用 axios 响应拦截器

axios.interceptors.response.use(response => {
  update.update_from_cookies();
  return response;
});

函数“update_from_cookies”试图获取名为“js-force”的 cookie,但它没有找到它,尽管我知道它正在发送

import Cookie from 'js-cookie';
import store from './store';

export function update_from_cookies() {
  let logged_in = Cookie.get('js-force');
  console.log('cookie ' + logged_in);
  if (logged_in && JSON.parse(logged_in)) {
    store.commit('logged_in', true);
  } else {
    store.commit('logged_in', false);
  }
}

我还看到了向 axios 调用添加参数的各种建议,但这些也不起作用。

我将不胜感激有关如何使用 axios 或与 Vue 一起使用的类似包处理 cookie 的一些建议

谢谢

【问题讨论】:

  • 您是否尝试将withCredentials 设置为true?
  • 我确实尝试将 withCredentials 添加为 true,但我没有正确执行。最终我发现正确的格式或者 axios 调用是 this.axios.post(uri, this.sfuser, {withCredentials: true}) .then( () => { this.$store.commit('change', this .sfuser.username); this.$router.push( {name : 'home' }); }) .catch( () => { });

标签: node.js express vue.js axios session-cookies


【解决方案1】:

问题已解决。我在 axios 调用中使用了错误的语法

正确的语法将 {withCredentials: true} 作为最后一个参数

  this.axios.post(uri, this.sfdata, {withCredentials: true})
    .then( () =>   {
      this.$router.push( {name : 'home' });
    })
    .catch( () => {
    });

【讨论】:

    猜你喜欢
    • 2017-07-02
    • 2017-09-27
    • 1970-01-01
    • 2021-04-06
    • 2019-02-02
    • 2018-07-23
    • 2018-12-22
    • 2018-05-20
    • 2018-12-06
    相关资源
    最近更新 更多