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

ReactJS向AWS ECS服务器发送Cookie失败问题求助

MERN栈跨域Cookie回传问题排查与修复

问题场景

后端API部署至http://44.198.159.229:5000,前端运行在localhost:3000。前端能接收后端Set-Cookie响应,但调用/api/auth/check的GET请求时,Cookie被浏览器拦截未回传。手动访问API路由正常,本地同域部署也正常,仅Axios跨域请求出现该问题。

相关代码

后端Express核心配置

const corsOptions = {
    credentials: true,
    origin: "http://localhost:3000",
    optionsSuccessStatus: 200,
};

const app = express();

app.set("trust proxy", true);

// 中间件
app.use(cors(corsOptions));
app.use(cookieParser());

app.use(
    session({
        secret: "somethingsecretgoeshere",
        resave: false,
        saveUninitialized: false,
        cookie: {
            httpOnly: false,
            secure: false,
            maxAge: 10 * 60 * 100000,
            sameSite: 'none'
        },
    })
);

app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(passport.initialize());
app.use(passport.session());

passportConfig(passport);

app.use("/api", auth_routes);
app.use("/api", major_requirement_routes);
app.use("/api", user_course_routes);

export default app;

认证路由代码

router.get("/auth/check", (req, res) => {
    console.log(req.user)
    console.log(req.cookies)
    if (req.user) {
        User.findOne({netId: req.user}, function (err, docs) {
            if (err) {
                console.log(err);
            } else {
                res.json({
                    auth: true,
                    user: req.user,
                    courseList: docs.courseList,
                    semesterList: docs.semesterList,
                    major: docs.major,
                    creditsApplied: docs.creditsApplied,
                    emailAddress: docs.emailAddress,
                });
            }
        });
    } else {
        res.json({auth: false, id: null});
    }
});

前端Axios全局配置

import axios from "axios";

const backend_url = "http://44.198.159.229:5000/api"

export default axios.create({
    withCredentials: true,
    baseURL: backend_url,
});

前端认证请求代码

axios
    .get("auth/check", { withCredentials: true, credentials: 'include' })
    .then(({ data}) => {
        console.log(data)
        if (data.auth) {
            setIsAuthenticated(true);
            setUser(data.user);
            setCourseList(data.courseList);
            setIsLoading(false);
        } else {
            setIsAuthenticated(false);
            setCourseList(undefined);
            setUser(undefined);
            setIsLoading(false);
        }
    })
    .catch(() =>
        console.log(
            "Something went wrong while trying to fetch your auth status."
        )
    );

问题修复方案

  1. 调整Cookie的secure属性:当设置sameSite: 'none'时,浏览器强制要求secure: true(仅HTTPS传输)。若为HTTP测试环境,可将sameSite改为'lax';生产环境建议配置HTTPS并开启secure: true。
  2. 统一Axios credentials配置:全局已设置withCredentials: true,请求时无需重复添加credentials: 'include',避免配置冲突。
  3. 验证CORS origin匹配:确保corsOptions中的origin与前端实际地址完全一致(含端口),生产环境建议使用具体域名而非localhost。
  4. 检查反向代理配置:后端设置了app.set("trust proxy", true),若部署在Nginx等反向代理后,需确保代理传递X-Forwarded-Proto等头信息,避免Cookie域名/协议设置错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 17:31:01