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

Next.js/React对接Express无法设置Cookie且fetch请求报错如何解决?

Next.js对接Express跨域Cookie设置问题修复方案

核心问题点

  • 后端CORS默认配置不符合跨域携带Cookie的要求,导致预检请求直接失败,触发Failed to fetch报错
  • 前端fetch请求未开启凭证携带配置,即使后端返回Set-Cookie头,浏览器也会拦截不会存储对应Cookie
  • 服务端发起的请求(放在getServerSideProps中)返回的Cookie不会自动同步到客户端浏览器,需要手动转发

后端代码修改

修改CORS配置,同时补充Cookie的跨域兼容属性:

const express = require("express");
const cookieParser = require("cookie-parser");
const cors = require("cors");

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 替换原有默认cors配置
app.use(cors({
  origin: "http://localhost:3000", // 替换为你的Next.js前端实际访问地址
  credentials: true // 允许跨域凭证传输
}));
app.use(cookieParser());

app.post("/", (req, res) => {
  // 补充Cookie属性,适配跨域场景
  res.cookie("token", req.body.token, {
    path: "/",
    sameSite: "lax", // 生产环境跨域需改为none并开启secure: true
    httpOnly: process.env.NODE_ENV === "production" // 生产环境开启防止XSS窃取Cookie
  }).send({ msg: "DONE" });
});

app.listen(5000, () => {
  console.log("running on http://localhost:5000");
});

前端代码修改

fetch请求新增credentials: 'include'配置,允许接收和携带跨域Cookie:

import styles from "../styles/Home.module.css";

export default function Home({ cookies }) {
  return (
    <div className={styles.container}>
      <h1>Cookies: {cookies}</h1>
      <button
        onClick={() => {
          fetch(`http://localhost:5000/`, {
            method: "post",
            headers: {
              "Content-Type": "application/json",
            },
            credentials: "include", // 新增该行配置
            body: JSON.stringify({ token: "ACBD" }),
          });
        }}
      >
        Genrate Cookies
      </button>
    </div>
  );
}

getServerSideProps场景补充说明

如果请求逻辑放在getServerSideProps中,属于Node.js服务端发起请求,拿到接口返回的set-cookie响应头后,需要手动设置到返回给客户端的响应头中,示例如下:

export async function getServerSideProps({ req, res }) {
  const apiRes = await fetch("http://localhost:5000/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ token: "ACBD" }),
  });
  // 手动转发Cookie到客户端
  const setCookie = apiRes.headers.get("set-cookie");
  if (setCookie) {
    res.setHeader("Set-Cookie", setCookie);
  }
  return {
    props: {}
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:06:08