NestJS CORS issus when using GraphQL

后端使用nest框架,开启了跨域资源共享,但是前端请求依然遇到问题

Access to XMLHttpRequest at 'http://161.489.630.200:9001/graphql/auth/login' from origin 'http://161.489.630.200:9000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

 之前的项目中如下代码是不会出现问题的

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // cors
  app.enableCors();

  app.useGlobalPipes(new ValidationPipe({ skipMissingProperties: true }));

  await app.listen(3000);
  console.log(`Application is running on: http://localhost:3000`);
}

bootstrap();

 但是这次因为用到了Graphql,所以参照 https://stackoverflow.com/questions/50949231/nestjs-enable-cors-in-production 进行了如下修改,问题解决了。

// main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  // cors
  app.enableCors({
    origin: true,
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
    credentials: true,
  });

  app.useGlobalPipes(new ValidationPipe({ skipMissingProperties: true }));

  await app.listen(3000);
  console.log(`Application is running on: http://localhost:3000`);
}

bootstrap();

 

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值