【问题标题】:How to active CORS in firebase functions with NestJs如何使用 NestJs 在 firebase 函数中激活 CORS
【发布时间】:2021-02-07 14:26:38
【问题描述】:

我正在使用此代码在 firebase 函数中运行我的后端

// Nest Dependencies
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ExpressAdapter } from '@nestjs/platform-express';
// Firebase Functions Dependencies
import * as functions from 'firebase-functions';
import * as express from 'express';
// Create a express server
const server = express();
const cors = require('cors');
// Create a NestServer With the Express server
const createNestServer = async (expressInstance: any): Promise<void> => {
  const app = await NestFactory.create(
    AppModule,
    new ExpressAdapter(expressInstance),
  );
  //Inititlize it
  await app.init();
};

// Create the google cloud function with the Nest Server(express server)
export const v1 = functions.https.onRequest(async (request, response) => {
  await createNestServer(server);
  server.use(cors({origin:true}))
  server(request, response);
});

但是我的 React 前端出现了这个 CORS 错误

跨域请求被阻止:同源策略不允许读取位于https://dev-api.mytingo.com/v1/user/teacher/groups/active?idTeacher=179 的远程资源。 (原因:缺少 CORS 标头“Access-Control-Allow-Origin”)。

我错过了什么? 感谢您的帮助

【问题讨论】:

    标签: node.js google-cloud-functions cors nestjs


    【解决方案1】:

    您可以尝试以下方法:

    const createNestServer = async (expressInstance: any): Promise<void> => {
      const app = await NestFactory.create(
        AppModule,
        new ExpressAdapter(expressInstance),
      );
      //enable cors here
      app.enableCors();
      //Inititlize it
      await app.init();
    };
    

    【讨论】:

      【解决方案2】:

      引用罗曼的回答:

      如果您遵循本教程:https://fireship.io/snippets/setup-nestjs-on-cloud-functions/

      然后,您将拥有与 NestJS 应用程序的 main.ts 文件相对应但用于生产的 index.ts(在 src 文件夹中)文件。所以你可以按照 Roman 的建议在这个地方激活 cors。有几个选项是可能的,这里是一个例子:

      export const createNestServer = async (expressInstance) => {
        const app = await NestFactory.create(
          AppModule,
          new ExpressAdapter(expressInstance),
        );
      
        const corsOptions = {
          methods: 'GET',
          preflightContinue: true,
          optionsSuccessStatus: 204,
          credentials: true,
          origin: ['http://localhost:8100/'],
        };
      
        app.enableCors(corsOptions);
      
        return app.init();
      };
      

      不要忘记在重新启动之前构建!

      npm run build
      firebase serve --only functions
      firebase deploy --only functions
      

      【讨论】:

        猜你喜欢
        • 2019-06-17
        • 2021-03-21
        • 2017-05-06
        • 1970-01-01
        • 2020-01-18
        • 1970-01-01
        • 1970-01-01
        • 2020-07-04
        • 2018-03-24
        相关资源
        最近更新 更多