nestjs cors
时间: 2023-09-02 11:11:47 浏览: 126
nestjs-crud
NestJS provides built-in support for Cross-Origin Resource Sharing (CORS) through the @nestjs/common package. CORS is a security feature implemented by web browsers that restricts web pages from making requests to a different domain than the one that served the web page. This can be problematic when developing APIs that are consumed by different domains.
To enable CORS in NestJS, you can use the @nestjs/common package to create a middleware that sets the Access-Control-Allow-Origin header. Here's an example of how to enable CORS for all routes:
```typescript
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept',
);
next();
})
.forRoutes('*');
}
}
```
In this example, the middleware function sets the Access-Control-Allow-Origin header to allow requests from any origin. The Access-Control-Allow-Headers header is also set to allow requests with the specified headers.
You can also configure CORS for specific routes by passing the route path as an argument to the forRoutes() method. For example, to enable CORS for a specific route:
```typescript
consumer
.apply((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept',
);
next();
})
.forRoutes('/api/users');
```
This middleware will only be applied to requests to the /api/users route.
阅读全文