企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## CORS 跨源资源共享(`CORS`)是一种允许从另一个域请求资源的机制。在底层,`Nest` 使用了Express的[cors](https://github.com/expressjs/cors) 包,它提供了一系列选项,您可以根据自己的要求进行自定义。 ### 开始 为了启用 `CORS`,必须调用 `enableCors()` 方法。 ```typescript const app = await NestFactory.create(AppModule); app.enableCors(); await app.listen(3000); ``` 该`enableCors()`方法需要一个可选的配置对象参数。这个对象的可用属性在官方 <a href="https://github.com/expressjs/cors#configuration-options" style="color:red;">CORS</a> 文档中有所描述。另一种方法是传递一个<a href="https://github.com/expressjs/cors#configuring-cors-asynchronously" style="color:red;">回调函数</a>,来让你根据请求异步地定义配置对象。 或者通过 `create()` 方法的选项对象启用CORS。将 `cors`属性设置为`true`,以使用默认设置启用CORS。又或者,传递一个 <a href="https://github.com/expressjs/cors#configuration-options" style="color:red;">CORS 配置对象</a> 或 <a href="https://github.com/expressjs/cors#configuring-cors-asynchronously" style="color:red;">回调函数</a> 作为 `cors` 属性的值来自定义其行为。 ```typescript const app = await NestFactory.create(AppModule, { cors: true }); await app.listen(3000); ``` 上述方法仅适用于 REST 端点。 要在 `GraphQL` 中启用 `CORS`,请将 `cors` 属性设置为 `true` 或在导入 `GraphQL` 模块时将 `CORS` 配置对象或回调函数作为 `cors` 属性值传递。 >**提醒**:CorsOptionsDelegate 解决方案尚不能与 apollo-server-fastify 包一起使用。 ~~~typescript GraphQLModule.forRoot({ cors: { origin: 'http://localhost:3000', credentials: true, }, }), ~~~