我尝试向Firebase函数发送一个简单的请求,但每次都会出现相同的错误...显然,Firebase函数没有收到我想从Axios请求传输的数据。
这是Firebase功能:
[...] // Some imports
exports.completeProfile = functions.https.onRequest((req, res) => {
// Debug
console.log(req);
console.log(req.body);
console.log(req.method);
console.log("Test: " + userId + ", " + profilePicture + ", " + username);
// We recover the data
const userId = req.body.userId; // return "undefined"
const profilePicture = req.body.profilePicture; // return "undefined"
const username = req.body.username; // return "undefined"
// we're checking to see if they've been transferred
if (!userId || !profilePicture || !username) {
// At least one of the 3 required data is not completed
console.error("Error level 1: missing data");
return res.status(400).send("Error: missing data");
}
[...] // (We have all the data, we continue the function)
});
这是我的Axios请求:
axios
.post(
'<FIREBASE CLOUD FUNCTION URL>',
{
userId: '12345667',
profilePicture: 'https://profilepicture.com/url',
username: 'test',
}
)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
当我运行Axios查询时,我总是遇到&#34;网络错误&#34;错误。以下是 console.log(错误); 给出的内容:
如何解决问题?谢谢你的帮助。
答案 0 :(得分:4)
将您的firebase代码更改为此
var cors = require("cors");
completeProfileFn = (req, res) => {
// Debug
console.log(req);
console.log(req.body);
console.log(req.method);
console.log("Test: " + userId + ", " + profilePicture + ", " + username);
// We recover the data
const userId = req.body.userId; // return "undefined"
const profilePicture = req.body.profilePicture; // return "undefined"
const username = req.body.username; // return "undefined"
// we're checking to see if they've been transferred
if (!userId || !profilePicture || !username) {
// At least one of the 3 required data is not completed
console.error("Error level 1: missing data");
return res.status(400).send("Error: missing data");
}
// (We have all the data, we continue the function)
};
// CORS and Cloud Functions export logic
exports.completeProfile = functions.https.onRequest((req, res) => {
var corsFn = cors();
corsFn(req, res, function() {
completeProfileFn(req, res);
});
});
这是一个CORS问题。