问题
I'm trying to send expo push notification via firebase cloud functions, in order to send notifications from the web app to devices that have downloaded the mobile app.
When I send the request from Postman, it works just fine... i get the ok response and the notification shows up on my phone. But when I try to make the request from the web app, i get this in the functions log:
Function execution took 22 ms, finished with status: 'crash'
Any ideas why is this happening? Couldn't find anything to explain this so far.
Here's my function:
exports.reportNotification = functions.https.onRequest((request, response) => {
const tokens = request.body.expoPushToken;
let messages = [];
tokens.forEach((token) =>
messages.push({
to: token,
title: "title",
body: "message",
sound: "default",
_displayInForeground: "true",
})
);
fetch("https://exp.host/--/api/v2/push/send", {
method: "POST",
headers: {
Accept: "application/json",
"Accept-encoding": "gzip, deflate",
"Content-Type": "application/json",
},
body: JSON.stringify(messages),
})
.then((res) => response.status(200).json({ res: res }))
.catch((err) => response.status(400).json({ error: err }));
});
My post request on Postman:
{
"expoPushToken": ["ExponentPushToken[xxx-xxxxxxxxxxxxx]"]
}
And I call the function with axios in the web app:
axios({
url: "reportNotification",
baseURL: functionsBaseURL,
method: "post",
data: {
expoPushToken: tokens,
},
})
I checked and the tokens on this request are in the same format that the one on Postman.
Thanks.
回答1:
It was a cors problem, solved with this modification:
exports.reportNotification = functions.https.onRequest((request, response) => {
cors(request, response, () => {
const tokens = request.body.expoPushToken;
let messages = [];
tokens.forEach((token) =>
messages.push({
to: token,
title: "title",
body: "message",
sound: "default",
_displayInForeground: "true",
})
);
axios.post("https://exp.host/--/api/v2/push/send", JSON.stringify(messages), {
headers: {
"Accept": "application/json",
"Accept-encoding": "gzip, deflate",
"Content-Type": "application/json",
},
})
.then((res) => response.status(200).json({ res: res }))
.catch((err) => response.status(200).json({ error: err }));
});
});
来源:https://stackoverflow.com/questions/62524771/firebase-cloud-function-http-request-crashing