【问题标题】:Enabling CORS in firebase functions在 firebase 函数中启用 CORS
【发布时间】:2020-07-04 15:19:53
【问题描述】:

我有以下代码:

const { v4: uuidv4 } = require('uuid')
const functions = require('firebase-functions')
const nodemailer = require('nodemailer')
const cors = require('cors')({ origin: true })
const gmailEmail = functions.config().gmail.email
const gmailPassword = functions.config().gmail.password
const mailto = functions.config().gmail.mailto
const mailTransport = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: gmailEmail,
    pass: gmailPassword
  }
})

exports.sendMail = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    const items = req.body.items.forEach(item => (
      `${item.quantity} x ${item.uuid} (${item.name})\n`
    ))
    if (req.method === 'POST') {
      const mailOptions = {
        from: gmailEmail,
        replyTo: gmailEmail,
        to: mailto,
        subject: `Order ${uuidv4()} from ${req.body.name} (${req.body.email})`,
        text: `Order\n\n${items}`
      }
      mailTransport.sendMail(mailOptions)
      res.status(200).send(JSON.stringify({ status: 'OK' }))
    } else {
      res.status(400).send(JSON.stringify({ status: 'method not allowed' }))
    }
  })
})

由于某种原因,它工作了一次,然后一直给我

Access to fetch at 'https://xxxxx.cloudfunctions.net/sendMail' from origin 'https://xxxx.com' 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.

我错过了什么?如果可能的话,我想避免使用 Express。

【问题讨论】:

  • 在单独的语句中尝试这些?常量应用程序 = 快递(); const cors = 要求('cors'); app.use(cors({ origin: true }));

标签: javascript firebase cors google-cloud-functions fetch


【解决方案1】:

要使用 Firebase 在 Cloud Functions 上配置 CORS,您需要配置和设置一些附加参数 - 如官方文档 here 中所述 - 以便 CORS 在您的应用程序中通过 HTTP 获得授权和执行。

您需要在应用程序上配置的设置示例中的参数如下:

const express = require('express'); 
const cors = require('cors')({origin: true}); 
const app = express(); 
app.use(cors({ origin: true }));

我建议您使用上述设置尝试一下,以便您在后端进行授权。

除此之外,来自社区的以下问题,还有一些与您类似问题的其他解决方案和用例,我认为它们应该可以帮助您实现配置,并且我认为您也应该检查一下。

如果这些信息对您有帮助,请告诉我!

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 2019-10-16
    • 2018-07-05
    • 1970-01-01
    • 2020-02-12
    • 2019-12-11
    • 2017-08-02
    • 2018-08-17
    • 2018-10-21
    相关资源
    最近更新 更多