【问题标题】:Nest and HTTP function - CORS嵌套和 HTTP 函数 - CORS
【发布时间】: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


【解决方案1】:

假设您的客户端是 Angular 应用程序,如果您正在运行客户端的本地开发版本,则可以使用代理配置文件使您的请求看起来好像来自同一来源:

proxy.conf.json

{
    "/api-default": {
        "target": "https://us-central1-<project>.cloudfunctions.net",
        "logLevel": "debug"
    }
}

您需要根据您调用 api 的方式配置此文件,然后使用以下命令启动本地应用程序:ng serve --proxy-config proxy.conf.json

另一种方法是在您的 NestJS 响应中添加适当的 CORS 响应标头:

@Post()
@Header('Access-Control-Allow-Origin', 'http://localhost:4200')
create() {
  return 'This action adds a new cat';
}

这将告诉客户端服务器允许提供的来源。

【讨论】:

    猜你喜欢
    • 2018-08-17
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-12
    • 2016-09-01
    • 2012-05-27
    相关资源
    最近更新 更多