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

NextJS中nextjs-cors的Origin数组类型配置不生效问题求助

解决nextjs-cors数组origin不生效问题

针对你使用nextjs-cors 2.1.2 + NextJS 13.1.1时,origin数组配置无效的问题,提供以下几种可行解决方案:

方案一:使用自定义origin验证函数

放弃直接传数组,改用函数动态校验请求来源,这是更可靠的方式:

import type { NextApiRequest, NextApiResponse } from 'next';
import NextCors from 'nextjs-cors';
import redisService from '../../../utils/services/redis-service';

type ResponseData = {
  message: string;
};

// 允许的域名列表
const allowedOrigins = [
  'https://sample1.com',
  'https://sample2.com',
  'http://sample3.com',
];

export default async function handler(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
  try {
    await NextCors(req, res, {
      methods: ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'],
      // 自定义origin验证函数
      origin: (origin) => {
        // 允许本地开发环境(origin为undefined的情况)
        if (!origin) return true;
        return allowedOrigins.includes(origin);
      },
      optionsSuccessStatus: 200,
    });
    const result = await redisService(req?.query?.redisKey);
    if (result) {
      res.status(200).json(result);
    } else {
      res.status(400).json({
        message: 'Error occured',
      });
    }
  } catch (err: any) {
    res.status(400).json({
      message: err?.message,
    });
  }
}

方案二:调整nextjs-cors版本

nextjs-cors 2.1.2可能存在数组origin解析的bug,尝试升级到最新稳定版(执行npm install nextjs-cors@latest),或者降级到2.0.0版本(执行npm install nextjs-cors@2.0.0),之后重新测试数组配置是否生效。

方案三:手动处理CORS(绕过nextjs-cors)

如果插件问题无法解决,可以直接在API路由中手动处理CORS逻辑,无需依赖nextjs-cors:

import type { NextApiRequest, NextApiResponse } from 'next';
import redisService from '../../../utils/services/redis-service';

type ResponseData = {
  message: string;
};

const allowedOrigins = [
  'https://sample1.com',
  'https://sample2.com',
  'http://sample3.com',
];

export default async function handler(req: NextApiRequest, res: NextApiResponse<ResponseData>) {
  // 处理OPTIONS预检请求
  if (req.method === 'OPTIONS') {
    const origin = req.headers.origin;
    if (origin && allowedOrigins.includes(origin)) {
      res.setHeader('Access-Control-Allow-Origin', origin);
    }
    res.setHeader('Access-Control-Allow-Methods', 'GET, HEAD, PUT, PATCH, POST, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    return res.status(200).end();
  }

  // 处理其他请求的CORS头
  const origin = req.headers.origin;
  if (origin && allowedOrigins.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
  }

  try {
    const result = await redisService(req?.query?.redisKey);
    if (result) {
      res.status(200).json(result);
    } else {
      res.status(400).json({
        message: 'Error occured',
      });
    }
  } catch (err: any) {
    res.status(400).json({
      message: err?.message,
    });
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 21:13:12