【发布时间】:2022-02-06 16:19:43
【问题描述】:
我有一个简单的 firebase 函数,它返回一个 hello world
exports.myFunc = functions
.runWith({
maxInstances: 1,
memory: "128MB"
})
.https.onRequest(async (request, response) => {
response.set("Content-Type", "text/plain");
response.status(200).send('Hello world!');
}
我通过带有这些标头的 POST 请求调用它:
> {
> host: 'localhost:5001',
> connection: 'keep-alive',
> pragma: 'no-cache',
> 'cache-control': 'no-cache',
> accept: '*/*',
> 'access-control-request-method': 'POST',
> 'access-control-request-headers': 'authorization,content-type',
> origin: 'http://localhost:8080',
> 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36',
> 'sec-fetch-mode': 'cors',
> 'sec-fetch-site': 'same-site',
> 'sec-fetch-dest': 'empty',
> referer: 'http://localhost:8080/',
> 'accept-encoding': 'gzip, deflate, br',
> 'accept-language': 'en-US,en;q=0.9'
> }
问题是我在尝试调用它时遇到了 CORS 错误,因为我是从托管在 firebase 上的 vue 应用程序调用它。好的,有道理,所以我阅读了一些关于 CORS 的文档,它抛出的第一个错误是:
from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
好的,我添加所需的标题:
exports.myFunc = functions
.runWith({
maxInstances: 1,
memory: "128MB"
})
.https.onRequest(async (request, response) => {
if (request.method === 'OPTIONS') {
response.set('Access-Control-Allow-Origin', '*');
response.status(204).send('');
} else {
// return hello world
}
}
我知道允许所有 (*) 是一种不好的安全做法,并且违背了 CORS 的某些目的,但这是为了测试。通过上述设置,我得到另一个 CORS 错误:
from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
好的,我再添加一些标题:
exports.myFunc = functions
.runWith({
maxInstances: 1,
memory: "128MB"
})
.https.onRequest(async (request, response) => {
if (request.method === 'OPTIONS') {
response.set('Access-Control-Allow-Headers', "authorization,content-type");
response.set('Access-Control-Allow-Origin', '*');
response.status(204).send('');
} else {
// return hello world
}
}
但是添加该标题从一开始就给我同样的错误! :
from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我已经尝试了所有随机标头组合、身份验证标头、凭据标头、启用所有标头方法等。没有组合似乎可以工作我做错了什么?我在网上找到的所有答案都告诉我添加
'Access-Control-Allow-Origin', '*'
是解决方案,但它不起作用?一个解决方案会导致另一个错误,依此类推。
这是我要返回的返回标头:
> [Object: null prototype] {
> 'x-powered-by': 'Express',
> 'access-control-allow-headers': 'authorization,content-type',
> 'access-control-allow-origin': '*'
> }
【问题讨论】:
标签: node.js firebase google-cloud-functions cors