【发布时间】:2020-06-14 22:20:14
【问题描述】:
我正在尝试将 Nest 与 Firebase HTTP 函数结合使用,但在从客户端调用时遇到了 CORS 错误。
这是我之前的设置:
declare const require: any
const functions = require('firebase-functions')
const cors = require('cors')({ origin: true })
const express = require('express')
const app = express()
app.use(cors)
const cb = (req, res) => res.status(200).send('success')
app.use(cb)
export default functions.https.onRequest(app)
上述工作正常(使用allAuthenticatedUsers 设置的 Cloud Functions Invoker 角色)。
这是我在 Nest 中的新设置:
import * as functions from 'firebase-functions'
import { NestFactory } from '@nestjs/core'
import { ExpressAdapter } from '@nestjs/platform-express'
import { Api_Module } from './api.module'
import express from 'express'
const server = express()
const create_nest_server = async (express_instance: express.Express) => {
const adaptor = new ExpressAdapter(express_instance)
const app = await NestFactory.create(Api_Module, adaptor)
app.enableCors({ origin: true })
await app.init()
return app
}
create_nest_server(server)
.then(v => console.log('Nest Ready'))
.catch(err => console.error('Nest broken', err))
export default functions.https.onRequest(server)
(来自https://fireship.io/snippets/setup-nestjs-on-cloud-functions/)
这会在客户端产生Access to fetch at 'https://us-central1-<project>.cloudfunctions.net/api-default/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.。
我还尝试了其他一些方法,例如:
declare const require: any
const cors = require('cors')({ origin: true })
const server = express()
server.use(cors)
// ...the rest
还有:
const create_nest_server = async (express_instance: express.Express) => {
const adaptor = new ExpressAdapter(express_instance)
const app = await NestFactory.create(Api_Module, adaptor, {
cors: {
origin: true,
}
})
app.enableCors()
await app.init()
return app
}
还有:
const nestApp = await NestFactory.create(AppModule, adapter, {
logger: new CoreLogger(),
cors: {
origin: '*',
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
credentials: true,
preflightContinue: false,
optionsSuccessStatus: 204,
},
})
以及使用不带任何参数的app.enableCors()。
非常感谢您的帮助。
【问题讨论】:
-
嗨@skwny,您可以查看here 提供的解决方案并验证它是否对您有帮助吗?这似乎与您测试的方法不同。
-
@gso_gabriel 感谢您提供链接,但这不是 Firebase 功能集成示例。如该链接所示,我确实尝试在嵌套应用程序引导期间使用
app.enableCors(),但不幸的是没有成功。 -
看看this other answer。我认为这可能会有所帮助。
-
@Ajordat 我已经看过那个帖子了,它也不是一个嵌套函数的例子
-
这是一个使用 JS 的 Firebase 函数,这似乎是您所需要的。你检查过那里显示的suggested documentation 吗?
标签: firebase cors google-cloud-functions nestjs