You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加credentials: 'include'导致JS Fetch请求PHP失败的问题及解决

跨域请求中Fetch API结合PHP Session的问题解决

问题背景

从HTML/PHP开发模式转向JS/PHP模式,使用JavaScript Fetch API时遇到跨域问题,核心需求是让PHP的$_SESSION变量正常保存。移除credentials: 'include'后代码可运行,但无法保存Session;尝试多种CORS配置组合仍未解决问题。

原代码

运行在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脚本中添加mode: 'cors',PHP脚本中添加header('Access-Control-Allow-Credentials: true');后,出现新错误:
Access to fetch at 'http://10.0.0.3/index.php' from origin 'http://10.0.0.2:3000' has been blocked by CORS policy: Request header field access-control-allow-credentials is not allowed by Access-Control-Allow-Headers in preflight response.

解决方案

修正后的代码如下:

修正后的JS代码

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');
    }
});
}

修正后的PHP代码

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');

内容的提问来源于stack exchange,提问作者Uxenora

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:10:30