我正在使用以下代码在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"(。
我缺少什么?感谢您的帮助
您可以尝试以下操作:
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();
};
引用Roman的回答:
如果您遵循本教程:https://fireship.io/snippets/setup-nestjs-on-cloud-functions/
然后,您将拥有index.ts(在src文件夹中(文件,该文件对应于NestJS应用程序的main.ts文件,但用于生产。所以你可以按照罗曼的建议在这个地方激活紧身胸衣。有几种选择是可能的,这里有一个例子:
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