javascript - 错误:发送后无法设置标头 node.js
问题描述
大家好,我对 node.js 相当陌生,我想知道我是否打了两次我不知道的电话。我收到一个错误:发送后无法设置标题。
export const hearingReminder = functions.https.onRequest((request, response) => {
console.log(request.body)
const payload = {
notification: {
title: 'Upcoming Hearing',
body: 'You have a hearing in one hour.',
}
};
const fcm = request.body.fcm
console.log(request.body.fcm)
try {
response.status(200).send('Task Completed');
return admin.messaging().sendToDevice(fcm, payload);
} catch (error) {
return response.status(error.code).send(error.message);
}
解决方案
admin.messaging().sendToDevice
在产生错误的情况下,您的代码尝试发送两次响应。与其在调用前发送 200 响应,不如仅在调用后发送。发送响应应该始终是函数中执行的最后一件事。
你的代码应该更像这样:
admin.messaging().sendToDevice(fcm, payload)
.then(() => {
response.status(200).send('Task Completed');
})
.catch(error => {
response.status(error.code).send(error.message);
})
请注意,您不需要为 HTTP 类型函数返回任何内容。你只需要确保处理所有的 Promise,并且只有在所有的 Promise 都解决后才发送响应。
推荐阅读
- android - 如何查看用户提出的无法从我们这边模拟的问题
- spring - Spring 事件发布者和多个监听器
- php - 安装由 adminpanel laravel 创建的 crud 项目时出错
- django - 超级用户创建错误 NOT NULL 约束失败
- stm32 - stm32和外接flash(w25q)连接问题
- nginx - 如何解决 nginx 中的“没有实时上游”错误?
- python - Python/Kivy 立即崩溃
- apache-camel - Apache Camel ActiveMQ 组件是否保证将消息传递给代理?
- javascript - jQuery - 使用 :contains 选择然后更改内容
- php - 如果它具有特定的 php 函数,有没有办法跟踪 html 标签?