首页 > 解决方案 > Axios 发出的 Drupal 和 CORS 请求:无法检查登录状态

问题描述

我正在创建独立的 html/javascript 应用程序,它应该与 Drupal 8.6.2 的 REST API 通信。我的应用使用 Vue.js,所以 ajax 请求是由 Axios 发送的。

我希望能够在同一域上以及通过来自另一个域的 CORS 操作该应用程序。假设我的 Drupal 位于https://drupal8.example.org

我可以使用以下代码从https://drupal8.example.org/apphttp://localhost/app登录和注销,而不会出现问题:

//Login
axios.post(
  "https://drupal8.example.org/user/login?_format=json",
  JSON.stringify({
    'name': "myusername",
    'pass': "mypassword"
}), {
  headers: {
    'Content-Type': 'application/hal+json'
  },
  withCredentials: true
}).
then(function (response) {
  //my code goes here
});

// logout
axios.post(
  "https://drupal8.example.org/user/logout?_format=json&token=" + logout_token, {}, {
    headers: {
      'Content-Type': 'application/hal+json'
    },
    withCredentials: true
  }
).
then(function () {
  //my code goes here
})

但是如果用户登录,我完全无法通过 CORS 检查:

//check login status
axios.get(
  "https://drupal8.example.org/user/login_status?_format=json", {}, {
    headers: {
      'crossDomain': true,
      'Content-Type': 'application/hal+json'
    },
    withCredentials: true
  }
).then(function (response) {
  console.log(response.data); // 1 from the same domain, 0 from localhost; should be 1 in both cases
});

如果我在浏览器窗口中检查 url https://drupal8.example.org/user/login_status?_format=json ,它会显示1,但 CORS 发出的请求返回0

问题的原因是什么以及如何解决?

标签: javascriptvuejs2corsaxiosdrupal-8

解决方案


好吧,解决方案很简单,但我还不知道原因。我必须为 Axios 设置默认选项

axios.defaults.withCredentials = true;

default.withCredentials显然,单独的请求与withCredentials发送的请求之间存在很大差异。不知道是bug还是功能。。。

这个答案帮助我找到了解决方案。


推荐阅读