部署在Vercel的NestJS接口遭Next.js客户端CORS报错求助
NestJS部署Vercel后Next.js客户端CORS错误问题
问题说明
将NestJS接口项目部署到Vercel平台后,从Next.js客户端发起HTTP请求时遭遇CORS错误。Postman、Swagger或本地环境下请求均正常,但React客户端请求始终失败。
已尝试的CORS配置
已按照官方文档配置CORS,也测试过多种自定义配置:
- 直接启用CORS:
const app = await NestFactory.create(AppModule, { cors: true });
- 指定源地址与请求方法的配置:
app.enableCors({ origin: ['http://localhost:3000', 'https://api-filmgen-pearl.vercel.app'], methods: ['GET', 'POST'], credentials: true, });
- 无参数启用CORS:
app.enableCors();
- 正则匹配源地址的配置:
app.enableCors({ credentials: true, origin: [/localhost:\d+$/, /\.vercel\.app$/, /\.herokuapp\.com$/], allowedHeaders: 'origin, content-type, accept, application/json', });
附Next.js配置代码
/** @type {import('next').NextConfig} */ const { i18n } = require('./next-i18next.config'); const nextConfig = { webpack(config) { config.module.rules.push({ test: /\.svg$/i, issuer: /\.[jt]sx?$/, use: ['@svgr/webpack'], }); return config; }, reactStrictMode: true, compiler: { styledComponents: true }, i18n } module.exports = nextConfig
内容的提问来源于stack exchange,提问作者Anzhela Nerukkh
相关产品推荐
相关产品推荐

