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

Express重定向在React/Next中触发CORS错误求助

解决方案:Express + Next.js 登出重定向引发的CORS错误

核心问题

你遇到的CORS错误本质是:前端通过Fetch发起跨域POST请求到API服务器,服务器返回重定向到localhost:3000/login/后,浏览器会将这个重定向请求视为跨域请求(因为初始请求是跨域的),但Next.js开发服务器默认未配置对应的CORS允许头,导致拦截。另外你的API CORS配置存在无效项:当credentials: true时,origin: "*"不被浏览器允许,带凭证的CORS请求必须指定具体Origin。


解决方案1:前端自主跳转(推荐)

放弃API重定向,改为返回成功状态,由前端处理页面跳转,彻底规避跨域重定向的CORS问题。

修改API登出路由:

authRouter.post('/logout', (req, res, next) => {
    req.logout(function(err){
        if(err){
            return next(err);
        }
        // 返回成功响应,不做重定向
        res.status(200).json({ message: '登出成功' });
    })
});

修改前端Fetch请求:

fetch(`https://api.invoice-app.naughty-cat.com/authentication/logout`,
      { 
        method: "POST",
        credentials: 'include', // Fetch标准用法,替换withCredentials
      })
.then(response => {
    if (response.ok) {
        // 客户端跳转登录页
        window.location.href = '/login/';
    }
})
.catch(err => console.log(err));

解决方案2:修正API的CORS配置

首先修复API端无效的CORS配置,将通配符Origin改为具体的前端域名:

app.use(
  cors({
    origin: "http://localhost:3000", // 生产环境替换为实际前端域名
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    credentials: true
  })
);

解决方案3:配置Next.js开发服务器的CORS

如果必须保留API重定向逻辑,需要让Next.js开发服务器允许跨域请求到登录路由:

  1. 安装依赖:
npm install cors
  1. 创建/修改next.config.js(Pages Router):
const cors = require('cors');

module.exports = {
  async middleware(req, res, next) {
    cors({
      origin: "*", // 或指定你的API域名
      credentials: true
    })(req, res, next);
  },
};
  1. 若使用App Router,创建middleware.js:
import { NextResponse } from 'next/server';
import cors from 'cors';

const corsMiddleware = cors({
  origin: "*",
  credentials: true,
});

export function middleware(req) {
  let res = NextResponse.next();
  
  return new Promise((resolve, reject) => {
    corsMiddleware(req, res, (result) => {
      if (result instanceof Error) {
        return reject(result);
      }
      resolve(res);
    });
  });
}

// 仅对登录路由应用CORS规则
export const config = {
  matcher: ['/login/:path*'],
};

关键说明

  • HTML链接跳转属于浏览器原生导航,不受CORS规则约束,因此可以正常工作;而Fetch是AJAX请求,严格遵循CORS政策。
  • 带凭证(credentials: true)的CORS请求不能使用通配符origin: "*",必须指定具体域名,否则浏览器会直接拒绝请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:34:57