使用NestJS+NextJS遇CORS跨域错误,请求协助解决
解决NestJS + NextJS 跨域(CORS)错误
方法一:在NestJS后端配置CORS
这是开发环境最直接的解决方式,通过NestJS内置的CORS支持允许前端源的请求。
全局CORS配置(main.ts)
在项目入口文件中开启全局CORS,指定允许的NextJS源:
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // 配置CORS规则 app.enableCors({ origin: 'http://localhost:3000', // 你的NextJS运行地址 credentials: true, // 若请求需要携带Cookie/凭证,开启此项 allowedHeaders: ['Content-Type', 'Authorization'], methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], }); await app.listen(3001); } bootstrap();
注意:生产环境请将
origin替换为你的前端实际域名,不要用*通配符(会导致凭证无法携带)。
路由/模块级CORS配置(可选)
如果只需要给特定接口(比如/auth/register)开启CORS,可以在控制器的路由上单独配置:
import { Controller, Post, Cors, Body } from '@nestjs/common'; import { AuthService } from './auth.service'; @Controller('auth') export class AuthController { constructor(private readonly authService: AuthService) {} @Post('register') // 仅对该路由开启CORS @Cors({ origin: 'http://localhost:3000' }) async register(@Body() registerDto: any) { return this.authService.register(registerDto); } }
方法二:在NextJS前端使用API路由代理(推荐生产环境)
通过NextJS的路由重写功能,将前端请求代理到后端,避免直接跨域请求,同时更安全(隐藏后端真实地址)。
配置next.config.js
在项目根目录的next.config.js中添加重写规则:
/** @type {import('next').NextConfig} */ const nextConfig = { async rewrites() { return [ { source: '/api/auth/:path*', destination: 'http://localhost:3001/auth/:path*', // 映射到后端API地址 }, ]; }, }; module.exports = nextConfig;
修改前端请求地址
将原来的后端直连地址http://localhost:3001/auth/register改为相对路径/api/auth/register,示例请求函数:
const register = async (values: z.infer<typeof RegisterSchema>) => { const res = await fetch('/api/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(values), }); return res.json(); };
这样请求会先经过NextJS服务器,再转发到后端,自然规避跨域问题。
内容的提问来源于stack exchange,提问作者HOPE RIDER - Phạm Hoàng
相关产品推荐
相关产品推荐

