提问人:Uxenora 提问时间:11/14/2023 最后编辑:Uxenora 更新时间:11/14/2023 访问量:71
凭据“include”导致获取失败 (js/php)
Credentials 'include' leads to failed to fetch (js/php)
问:
我一直在尝试使用 Javascript fetch API 来摆脱我的 html/php 例程,转而使用 javascript/php 例程。
我有点困惑,我读过很多关于这方面的文章,我认为我的问题来自标题 Access-Control-Allow-Origin。我尝试了许多可能的组合,但仍然找不到解决方案。
如果我删除“credentials: ”include“,我的代码可以工作,只是 $_SESSION 变量没有保存在 PHP 中(这实际上是我背后的主要目标)。
以下是在 10.0.0.2 : 3000 上运行的 JS 代码:
const fetchVar = (bodyVar, module) => {
fetch("http://10.0.0.3/index.php", {
method: 'POST',
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Access-Control-Allow-Origin": "http://10.0.0.3",
"Access-Control-Allow-Credentials": "true"
},
credentials: "include",
body: bodyVar
}).then((r) => {
if(r.ok) {
r.json().then((r) => {
if(!r.hasOwnProperty('error')) {
console.log(r);
} else {
console.log(r);
}
});
}
else {
console.log("error');
}
});
}
这里是运行在 10.0.0.3 : 80 上的 PHP 代码:
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Origin: http://10.0.0.2:3000');
这两个代码都更长,但我认为这就是问题所在,因为正如我之前所说,一旦删除了凭据,它就会起作用(也适用于“凭据:同源”)。
提前感谢您的回答:)
编辑:
我添加到了我的 fetch 脚本和我的 php 脚本中。因此,我收到一个新错误:mode: 'cors',
header('Access-Control-Allow-Credentials: true');
CORS 策略已阻止从源“http://10.0.0.2:3000”在“http://10.0.0.3/index.php”处提取:在预检响应中,Access-Control-Allow-Headers 不允许请求标头字段 access-control-allow-credentials。
溶液:
感谢 ADyson,我们为您提供了解决方案:
const fetchVar = (bodyVar, module) => {
fetch("http://10.0.0.3/index.php", {
mode: 'cors',
method: 'POST',
headers: {
"Accept": "application/json"
},
credentials: "include",
body: bodyVar
}).then((r) => {
if(r.ok) {
r.json().then((r) => {
if(!r.hasOwnProperty('error')) {
console.log(r);
} else {
console.log(r);
}
});
}
else {
console.log("error');
}
});
}
和:
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Origin: http://10.0.0.2:3000');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json');
答:
删除
"Access-Control-Allow-Origin": "http://10.0.0.3",
"Access-Control-Allow-Credentials": "true"
从您的 JS 代码。这些应该是响应标头,在客户端代码中没有意义 - 如果客户端可以决定这些事情,那么 CORS 将完全没有意义! 此外,其中之一显然是
不允许请求标头字段 access-control-allow-credentials
您报告的错误。
评论
"Access-Control-Allow-Origin": "http://10.0.0.3", "Access-Control-Allow-Credentials": "true"
credentials: "include",
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
bodyVar