Gia*_*dis 5 javascript node.js cors firebase google-cloud-functions
我有一个通用的云功能:
const functions = require('firebase-functions');
const cors = require('cors')({ origin: true });
exports.helloWorld = functions.https.onRequest((request, response) => {
cors(request, response, () => {
res.status(200).send("Hello from Firebase!");
});
});
Run Code Online (Sandbox Code Playgroud)
我使用 axios 从客户端调用它:
axios
.get(
"https://us-central1-dev-imcla.cloudfunctions.net/helloWorld",
)
.then((res) => {
console.log(res);
})
.catch(er=>{
console.log(er);
})
Run Code Online (Sandbox Code Playgroud)
我有两个问题:
从源“http://localhost:8080”访问“https://myurl/helloWorld”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。xhr.js?b50d:178 获取 https://us-central1-dev-imcla.cloudfunctions.net/helloWorld net::ERR_FAILED
错误:禁止 您的客户端无权从此服务器获取 URL /helloWorld。
错误:请求失败,在 XMLHttpRequest.handleLoad (xhr.js?b50d:61) 处的 createError (createError.js?2d83:16) 处解决 (settle.js?467f:17) 处,状态代码为 403
问题是我都是经过身份验证的用户,并且我在云代码中有 cors 包。
需要添加以下内容来处理云功能中的CORS 请求:
exports.corsEnabledFunction = (req, res) => {
// 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') {
// Send response to OPTIONS requests
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Allow-Headers', 'Content-Type');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
} else {
res.send('Hello World!');
}
};
Run Code Online (Sandbox Code Playgroud)
你可以尝试一下这个例子。这是guthub 存储库,其中包含完整代码。