【发布时间】:2020-06-26 12:56:16
【问题描述】:
我有一个谷歌云功能。我为我的项目创建了凭据,并授权 http://localhost 和 http://localhost:3000 作为来源。我还有一个 Google 用户帐户,我将其赋予了 cloudfunctions.functions.invoke 角色。我通过转到控制台中的云功能并展开“Cloud Functions Invoker”项目来确认这一点,并在其中看到我的帐户。
我可以通过 curl 成功访问该功能。
curl https://[google-cloud-server]/test5 -H "Authorization: bearer my-identity-token"
但是,如果我尝试从我的 React 应用程序调用该函数(我尝试了 axios 和 fetch),我会收到以下错误......
从源“http://localhost:3000”对“https://[google-cloud-server]/test5?a=b”处的 XMLHttpRequest 的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问控制允许来源” ' 请求的资源上存在标头。
需要注意的几件事...
- 如果我让所有用户都可以访问该函数,则不会出现 CORS 问题
- 通过日志记录,我已经确认,在安全的情况下,请求永远不会到达我有我的 CORS 代码用于检查飞行前选项的函数。这是有道理的,因为它应该由谷歌保护。但是我在 Google Cloud 函数上找到的所有文档都在讨论从函数内部处理与 CORS 相关的内容。在我的 React 应用程序的请求到达我的功能之前,它正在响应它。我不知道什么/在哪里。
我在这篇文章中添加了这么多标签,因为我真的不知道是哪一层导致了问题。我可能正在做一些非常明显/愚蠢的事情,但我没有想法!
云功能....
exports.test5 = (req, res) => {
console.log('function invoked');
// Set CORS headers for preflight requests
// Allows GETs from any origin with the Content-Type header
// and caches preflight response for 3600s
res.set('Access-Control-Allow-Origin', '*');
if (req.method === 'OPTIONS') {
console.log('Determined it is OPTIONS request');
// Send response to OPTIONS requests
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Allow-Headers', 'Authorization');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
} else {
console.log('Main function body');
res.send('Hello World!');
}
};
来自 React 客户端的调用...
const config =
{
params: payload,
headers:
{
Authorization: `bearer ${window.IDENTITY_TOKEN}`
}
};
axios.get(url, config)
.then((res) => {
...
})
.catch((err) => {
handleError(err);
});
有什么想法吗? 谢谢
【问题讨论】:
标签: node.js reactjs cors google-cloud-functions