未为 Firebase 云功能启用 Cors
Posted
技术标签:
【中文标题】未为 Firebase 云功能启用 Cors【英文标题】:Cors not being enabled for firebase cloud functions 【发布时间】:2021-04-08 16:13:10 【问题描述】:我正在使用 cors npm 包来解决 cors 问题,但无济于事。这以前可以工作,但是当我切换到我的开发环境时,我不断收到此错误:
Access to fetch at 'https://carside.firebaseapp.com/sendsmstoconsumer' from origin 'https://carside.web.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
这就是我的函数代码的设置方式:
const functions = require('firebase-functions')
const express = require('express')
const app = express()
const accountSid = 'SECRET'
const authToken = 'SECRET'
const client = require('twilio')(accountSid, authToken)
const cors = require('cors')
// Enable cors for everything
// TODO: Re-enable cors at a later date
// src: https://www.npmjs.com/package/cors
app.use(cors())
app.post('/sendsmsverificationmessage', cors() ,(request, response) =>
client.verify.services('SECRET')
.verifications
.create(to: request.body.phone, channel: 'sms')
.then(verification =>
response.send("Your verification code has been sent to your phone!" )
);
)
exports.app = functions.https.onRequest(app)
【问题讨论】:
app.use(cors())
使所有页面都可以通过 cors 访问
是的,应该是我仍然不断收到无法访问的错误
我现在收到此错误has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
【参考方案1】:
你需要:
const cors = require('cors')(origin: true);
另见:
Enabling CORS in Cloud Functions for Firebase【讨论】:
【参考方案2】:在我看来没问题,也许检查一下您在进行更改后是否重新启动了快速服务器。否则,我不使用 cors 包,而是使用来自https://enable-cors.org/server_expressjs.html 的 sn-p * 提供所有访问权限,但可以将其替换为您要授予访问权限的特定域。
编辑:另外,您使用 cors() 两次。一次进入 app.use() 并再次进入您的路线。我认为这不会导致 cors 不起作用,但这是不必要的。
app.use(function(req, res, next)
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
);
【讨论】:
我摆脱了 cor 并开始使用 app.use(cors) 但它仍然无法正常工作。这是我现在得到的错误“对预检请求的响应未通过访问控制检查:请求的资源上不存在'Access-Control-Allow-Origin'标头。”【参考方案3】:使用外部库处理 OPTIONS 调用 https://www.npmjs.com/package/cors
【讨论】:
以上是关于未为 Firebase 云功能启用 Cors的主要内容,如果未能解决你的问题,请参考以下文章
Firebase Firestore 错误:未为“对象”类定义运算符“[]”