NestJS 在生产中启用 cors

typescriptJS

1个回答

写回答

XueerC

2025-08-21 14:40

+ 关注

JS
JS

在实际的Web开发中,跨域资源共享(CORS)是一个非常常见的问题。当我们的前端应用程序运行在一个与后端服务不同的域名下时,浏览器会自动阻止前端应用程序与后端服务进行跨域请求。为了解决这个问题,我们可以使用NestJS框架提供的cors中间件。

什么是CORS?

跨域资源共享(CORS)是一种机制,它允许浏览器向不同域名下的服务器发送跨域请求,并且服务器可以决定是否接受这些请求。默认情况下,浏览器只允许同源请求,即前端应用程序和后端服务运行在同一个域名下。

在NestJS中启用CORS

在NestJS中,我们可以通过在应用程序的配置中启用cors中间件来解决跨域问题。首先,我们需要安装cors包:

$ npm install --save @nestJS/config

然后,在主模块(通常是app.module.ts)中导入ConfigModule:

typescript

import { Module } from '@nestJS/common';

import { ConfigModule } from '@nestJS/config';

@Module({

imports: [ConfigModule.forRoot()],

})

export class AppModule {}

接下来,我们需要在配置文件中添加CORS配置。在根目录下创建一个名为.env的文件,并添加以下内容:

CORS_ORIGIN=http://localhost:3000

在这个例子中,我们将允许来自http://localhost:3000域名的请求。

然后,在主模块中使用ConfigService来获取CORS_ORIGIN配置:

typescript

import { Module } from '@nestJS/common';

import { ConfigModule, ConfigService } from '@nestJS/config';

import { APP_FILTER } from '@nestJS/core';

import { HttpExceptionFilter } from './common/filters/http-exception.filter';

@Module({

imports: [ConfigModule.forRoot()],

providers: [

ConfigService,

{

provide: APP_FILTER,

useClass: HttpExceptionFilter,

},

],

})

export class AppModule {}

最后,在主模块的配置中启用cors中间件:

typescript

import { Module } from '@nestJS/common';

import { ConfigModule, ConfigService } from '@nestJS/config';

import { APP_FILTER, APP_INTERCEPTOR } from '@nestJS/core';

import { HttpExceptionFilter } from './common/filters/http-exception.filter';

import { LoggingInterceptor } from './common/interceptors/logging.interceptor';

@Module({

imports: [ConfigModule.forRoot()],

providers: [

ConfigService,

{

provide: APP_FILTER,

useClass: HttpExceptionFilter,

},

{

provide: APP_INTERCEPTOR,

useClass: LoggingInterceptor,

},

],

})

export class AppModule {}

现在,我们已经成功在NestJS应用程序中启用了CORS中间件。通过配置CORS_ORIGIN,我们可以指定允许的域名。这样,前端应用程序就可以与后端服务进行跨域请求了。

在本文中,我们介绍了在NestJS中启用CORS的方法。通过使用cors中间件,我们可以解决前端应用程序与后端服务之间的跨域问题。通过简单的配置,我们可以指定允许的域名,从而实现安全的跨域请求。

希望本文对你有所帮助!如果你有任何疑问或建议,请随时留言。谢谢阅读!

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号