我编写并部署了一个支持 CORS 的 Firebase Cloud 函数:
const cors = require('cors')({
origin: true
});
...
exports.test = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const idToken = req.query.idToken;
admin.auth().verifyIdToken(idToken)
.then((decoded) => {
var uid = decoded.uid;
return res.status(200).send(uid);
})
.catch((err) => res.status(401).send(err));
});
});
我使用 Axios 包从 React 应用程序调用 HTTP 触发器:
firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
// Send token to your backend via HTTPS
// ...
console.log(idToken);
axios.get('https://XXX.cloudfunctions.net/test?idToken='+idToken)
.then(response => console.log(response));
}).catch(function(error) {
// Handle error
});
不幸的是,当在本地服务器上运行该应用程序时,我仍然收到错误:
Failed to load...Redirect From..to..
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
PS。我已经使用过报告here的程序
最佳答案
我找到了答案here
exports.test = functions.https.onRequest((req, res) => {
cors(req, res, () => {});
const idToken = req.query.idToken;
admin.auth().verifyIdToken(idToken)
.then((decoded) => {
var uid = decoded.uid;
return res.status(200).send(uid);
})
.catch((err) => res.status(403).send(err));
});
关于javascript - 调用 Cloud Function HTTP 触发器时发生 CORS 策略错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49764827/