【问题标题】:Cannot set headers after they are sent to client Expressjs router将标头发送到客户端 Expressjs 路由器后无法设置标头
【发布时间】:2020-02-19 10:21:31
【问题描述】:

我收到错误无法在 express js 上设置标题,我认为问题是必须编写 setHeader,我已设置但仍不能,这是我的代码:

router.get('/cek', (req, res) => {
const child = execFile(commandd, ['-c', 'config', 'GSM.Radio.C0']);
child.stdout.on('data', 
    function (data) {
        value = (JSON.stringify(data));
        x = value.split('.');
        y = JSON.stringify(x[2])
        result = y.replace(/\D/g, "");
        res.setHeader('Content-Type', 'text/html');
        res.send(result);
    }
);

child.stderr.on('data',
    function (data) {
        console.log('err data: ' + data);
    }
);

});

这两天我已经厌倦了修复这个错误,但仍然无法解决,有人可以帮忙吗?

【问题讨论】:

  • data 事件将触发多次,一次生成来自stdout 的一段文本。您似乎将其视为一次性传递所有文本。假设文本相对较少,您可以连接 data 事件中的所有块,然后在 close 事件中发送。根据具体情况,还可以使用其他方法。
  • 当您在调用 res.send 方法后尝试执行某些操作时,通常会发生此错误。您可以尝试添加两件事:1)在 res.send 之前返回,因此 /cek 的请求将被阻塞,2)在 stderr 上添加 res.send(err)。在这两种情况下,某些事情都可能引发您的错误
  • 谢谢@FedericoIbba,在下面回答这是可行的..

标签: javascript express vue.js


【解决方案1】:

正如Frederico Ibba 所述,这通常是在发送 res.send 并且仍在处理数据之后引起的......您的解决方法可能只是在使用res.send 发送之前接收所有数据.你可以试试这个。

async function executeCommand() {
    return new Promise((resolve, reject) => {
        const child = execFile(commandd, ['-c', 'config', 'GSM.Radio.C0']);

        child.stdout.on('data', 
             function (data) {
                value = (JSON.stringify(data));
                x = value.split('.');
                y = JSON.stringify(x[2])
                result = y.replace(/\D/g, "");

                resolve(result);
             }
        );

        child.stderr.on('data',
           function (err) { // Renamed data for err for clarification
               reject(err);
           }
        );
    });
}

router.get('/url', async (req, res) => {
    try {
        const result = await executeCommand();
        res.setHeader('Content-Type', 'text/html');
        res.send(result);
    } catch(error) {
        // There was an error. I'm throwing a 500
        res.sendStatus(500);
    }
});

请注意这将是有效的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 2019-01-23
    • 2021-11-30
    • 2021-06-18
    • 2022-01-14
    • 2021-04-07
    • 1970-01-01
    相关资源
    最近更新 更多