javascript - 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/app和http://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。
问题的原因是什么以及如何解决?
解决方案
好吧,解决方案很简单,但我还不知道原因。我必须为 Axios 设置默认选项:
axios.defaults.withCredentials = true;
default.withCredentials
显然,单独的请求与withCredentials
发送的请求之间存在很大差异。不知道是bug还是功能。。。
这个答案帮助我找到了解决方案。
推荐阅读
- asp.net-web-api - 您是否应该将 Newtonsoft 添加到 WebAPI 项目或使用嵌入 WebAPI 的 Newtonsoft?
- amazon-dynamodb - 通过在 EMR 上运行的 PySpark 中的 Glue 数据目录访问 DynamoDB 时,绝对 URI 异常中的相对路径
- python - 需要帮助将源和目标端口号输出给用户,使用 Python 和 dpkt 从 pcap 文件中读取
- simulink - 一个循环后输出力为零
- ios - 操作无法完成。(NSURLErrorDomain 错误 -1011。)
- reactjs - react js中的表单验证库
- javascript - 根据在 ngfor 动态列表中的单击更改文本状态
- android - 谷歌应用商店不能同时安装两个应用
- python-3.x - Google Adwords 脚本在 AWS Lambda 上运行:[Errno 30] 只读文件系统:'/home/sbx_user1051'
- javascript - 返回承诺的函数未按预期工作