首页 > 解决方案 > 错误:发送后无法设置标头 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);

    }

标签: javascriptnode.jsgoogle-cloud-functions

解决方案


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 都解决后才发送响应。


推荐阅读