新建一个跨域中间件(如:cors.middleware.ts),并把它导入到项目根目录的app.modules.ts里面使用。
中间件代码如下:
import { Injectable, NestMiddleware } from "@nestjs/common"; @Injectable() // 跨域中间件 export class CorsMiddleware implements NestMiddleware { use(req: any, res: any, next: () => void) { res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE"); res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); next(); } }
在app.modules.ts里导入并使用:
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { AppController } from './app.controller'; import { AppService } from './app.service'; import { CorsMiddleware } from './cors.middleware'; @Module({ imports: [], controllers: [AppController], providers: [AppService], }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer.apply(CorsMiddleware).forRoutes("*"); } }
最后,重启服务,即可。
标签:03,06,跨域,res,app,中间件,Access,import From: https://www.cnblogs.com/iuniko/p/18056154