0

私はノード js を使用しています。また、他のサードパーティの共同 URL を要求しています。

このコードを実行すると、エラーが発生します。送信後にヘッダーを設定できません。

私がどんな間違いをしたのかわかりません。

参考までに: https://github.com/mcollina/node-coap

コード:

var app = require('express');
var router = app.Router();
var coap = require('coap');
var Q = require('q');
router.get('/test', function(req, res, next) {    
    var result = {
        resp : {},
    };    
    Q(result).then(function(result) {
        var deferred = Q.defer();    
        var coapConnection = {
            host : 'abcd.com',
            pathname : '/get',
            method : 'GET',
            port : '5683',
            confirmable : true
        };
        var req = coap.request(coapConnection);
        req.write(JSON.stringify(result.body));
        req.on('response', function(response) {
            var d = response.payload;
            result.resp.response = JSON.parse(d.toString('utf8'));
            deferred.resolve(result);
            response.pipe(process.stdout);
            response.on('end', function() {
                //process.exit(0);
                res.send(result.resp);
            });
        });
        req.end();
        return deferred.promise;
    }).then(function(result) {
        result.resp.status = 'Success';
        res.send(result.resp.response);
    }).fail(function(result) {
        result.resp.status = 'Error';
        res.send(result.resp);
    });

});

module.exports = router;

エラー:

throw new Error('Can\'t set headers after they are sent.');
          ^
Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
    at ServerResponse.res.set.res.header (test/node_modules/express/lib/response.js:524:10)
    at ServerResponse.res.json (test/node_modules/express/lib/response.js:189:36)
    at ServerResponse.res.send (test/node_modules/express/lib/response.js:118:21)
    at IncomingMessage.<anonymous> (test/routes/coap/trigger.js:111:9)
    at IncomingMessage.emit (events.js:129:20)
    at endReadableNT (test/node_modules/coap/node_modules/readable-stream/lib/_stream_readable.js:865:12)
    at afterTickTwo (test/node_modules/coap/node_modules/readable-stream/node_modules/process-nextick-args/index.js:27:10)
    at process._tickCallback (node.js:355:11)

誰でもこの問題の解決策を教えてください。ありがとう。

4

2 に答える 2

1

エラー メッセージは、リプレイをクライアントに送信した後でヘッダーを設定しようとしたことを示しています。あなたの場合、問題は res.send が2回呼び出されることです。応答イベントが呼び出されたときに送信し、その後機能します。

この場合、Express は nodejs 自体とは少し異なります。

于 2016-09-01T13:38:52.430 に答える
0

あなたの問題は、おそらくサイトを複数回作成することにあります。エラーは、ヘッダー (エルゴ、ページ) が既に作成されており、再作成しようとしていることを意味します。

ここでの犯人は次のコードです。

response.on('end', function() {
    //process.exit(0);
    res.send(result.resp);
});

競合するもの:

.then(function(result) {
    result.resp.status = 'Success';
    res.send(result.resp.response);
})

後者は最初のものを覆そうとするからですres.send()

于 2016-09-01T13:38:10.507 に答える