简体   繁体   English

错误:发送 node.js 后无法设置标头

[英]Error: Can't set headers after they are sent node.js

hi guys im fairly new to node.js and I was wonder if I am making a call twice that I am unaware of.大家好,我是 node.js 的新手,我想知道我是否拨打了两次我不知道的电话。 I am getting a Error: Can't set headers after they are sent.我收到一个错误:发送后无法设置标头。

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);

    }

Your code is attempting to send a response twice, under the condition that admin.messaging().sendToDevice generates an error.admin.messaging().sendToDevice产生错误的情况下,您的代码尝试发送两次响应。 Instead of sending the 200 response before the call, only send it after the call.而不是在调用之前发送 200 响应,只在调用之后发送。 Sending the response should always be the very last thing performed in your function.发送响应应该始终是您的函数中执行的最后一件事。

Your code should be more like this:你的代码应该更像这样:

    admin.messaging().sendToDevice(fcm, payload)
    .then(() => {
        response.status(200).send('Task Completed');
    })
    .catch(error => {
        response.status(error.code).send(error.message);
    })

Note that you don't need to return anything for HTTP type functions.请注意,您不需要为 HTTP 类型函数返回任何内容。 You just need to make sure to handle all the promises, and only send the response after all the promises are resolved.你只需要确保处理所有的承诺,并且只有在所有的承诺都得到解决后才发送响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM