簡體   English   中英

錯誤:發送 node.js 后無法設置標頭

[英]Error: Can't set headers after they are sent 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 類型函數返回任何內容。 你只需要確保處理所有的承諾,並且只有在所有的承諾都得到解決后才發送響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM