【发布时间】:2020-06-19 17:58:02
【问题描述】:
在我的反应应用程序中,我正在向云函数名称和电话发送具有 2 个属性的发布请求,但在反应应用程序中返回来自 CORS 的限制,我正在使用带有 Typescript 的云函数 这是我的反应应用程序中的代码
axios
.post(
"https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback",
{
name: `${this.state.contactName}`,
phone: `${this.state.phone}`,
}
)
.then(function(response) {
// eslint-disable-next-line no-console
console.log(response);
})
.catch(function(error) {
// eslint-disable-next-line no-console
console.log(error);
});
}); ```
这是来自我的云功能:
exports.firestoreTtlCallback = functions.https.onRequest(async(req , res) => {
res.set('Access-Control-Allow-Origin', "*")
res.set('Access-Control-Allow-Methods', 'GET, POST')
res.set('Access-Control-Allow-Headers', 'Content-Type');
const name = req.body.name;
console.log(name)
//recibir nombre de contacto y numero de telefono
const payload = req.body as ExpirationTaskPayload
try {
// buscar usuario y obtener token
const user = await db.collection('users').doc(payload.uid).get()
const data:any = user.data()
const counter = await admin.firestore().collection("users").doc(payload.uid).collection("kards").doc("0").collection("kardsRef").get();
const doc = await admin.firestore().doc(`/users/${payload.uid}/kards/0/kardsRef/${counter.size}`)
doc.set({ msg: "hola" })
var message = {
data: {
score: '850',
time: '2:45'
},
token: data.token
};
//enviar notificacion
await admin.messaging().send(message)
// Response is a message ID string.
// borrar notificacion firestore
await admin.firestore().doc(payload.docPath).delete()
return res.status(200).send(`Task has been executed`);
}
catch (error) {
console.error(error)
return res.status(500).send(error)
}
});
这是我得到的错误:
从源“http://localhost:3000”获取“https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback”的访问权限已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。
【问题讨论】:
-
问题中引用的错误消息表明
https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback端点未配置为以 CORS 工作所需的方式响应 OPTIONS 请求。该端点必须配置为以 200 OK 成功响应响应未经身份验证的 OPTIONS 请求。现在它显然正在响应一些其他 HTTP 状态代码:可能是 405 错误或其他一些 4xx 错误。 -
是的,但我使用 res.set(Access-Control-Allow-Headers) 进行了配置,没有我的 try-catch 工作正常,但是当我将它放入我的函数时会出现该消息跨度>
-
你检查过实际的 HTTP 状态码是什么吗?您可以使用浏览器开发工具中的网络窗格进行检查。
-
它是:错误:请求失败,状态码为 500
-
是的,你有一个 500 问题。您没有 CORS 问题。如果您修复了 500 错误的原因,您可能会发现您当前的 CORS 配置已经按预期工作。要解决 500 问题,您可以查看
https://us-central1-react-firebase-athentica-64987.cloudfunctions.net/firestoreTtlCallback端点的服务器日志,并查看在服务器响应该 500 之前那里记录了哪些消息。但是鉴于问题中显示的代码,它看起来可能是你自己的抛出 500 的代码——因为 try 块中的代码失败了。
标签: typescript google-cloud-firestore axios google-cloud-functions