Tuesday, 14 March 2017

Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)

I am developing a basic app with NodeJs and ZeroMQ, however I am currently facing an error, which i cannot seem to rid of. I have read solutions that suggest the program "sends" more than once, however i only have one "send" method. Please see code below...

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()));  
        response.end(); 

    });
});

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



via meji

No comments:

Post a Comment