错误:发送后无法设置标头。在ServerResponse.OutgoingMessage.setHeader(_http_outgoing.js:356:11)

时间:2017-03-14 16:35:31

标签: javascript node.js express zeromq

我正在使用NodeJs和ZeroMQ开发一个基本应用程序,但是我目前正面临一个错误,我似乎无法摆脱它。我已阅读建议程序“发送”不止一次的解决方案,但我只有一个“发送”方法。请参阅下面的代码......

var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var server_port = "3000";

/** app settings **/
var zeromq = require("zeromq");
var socket = zeromq.socket("req");/* sends request */
var protocol = "tcp://";
var ip = "192.000.0.000"; //server
var socket_port = "9998";
var url = protocol + ip + ":" + socket_port;

/*header settings*/
app.use(function (request, response, next) {
    response.setHeader('Content-Type', 'text/plain');
    response.setHeader( 'Access-Control-Allow-Origin', 'http://localhost:8888');
    response.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    response.setHeader('Access-Control-Allow-Credentials', true); 
    next();
});


app.use(bodyParser());

/** paths **/
app.post('/request', function (request, response) {
    var command = request.body;

    //connect to port
    socket.connect(url, function (error) {
        if (error) {
            console.log("connection error : ", error);
            process.exit(0);
        }
    });

    //response to front end
    socket.send(JSON.stringify(command));

    //recieve request
    socket.on('message', function (message) {

        //output message to console
        console.log("Recieved message @ : " + (new Date().toDateString()) + " : " + message.toString());

        //send response 
        response.status(200).send(JSON.stringify(message.toString()));  
    });
});

// test purposes
app.get('/recieve', function (request, response) {
    response.send("{ 'led': 'on' }").end();
});

/** start app **/
app.listen(server_port);

console.log("Server started on port: " + server_port);

1 个答案:

答案 0 :(得分:1)

问题在于:

response.status(200).send(JSON.stringify(message.toString()));  
response.end();

.send().end()都回复浏览器并且是多余的。只使用一个或另一个,但不能同时使用。

顺便说一下,你将字符串字符串化,所以你确实确保前端没有得到一个好的JSON(之后肯定会重新解析为JSON)。我不知道为什么每个人总是把所有东西都串起来并拒绝使用JSON?队长?