Chandan Kumar
Chandan Kumar

Reputation: 397

NodeJs Error: Can't set headers after they are sent

I am new to nodejs and stuck up with this Error:Can't set headers after they are sent. Below is my code. Please help. I used postman to test this code. It is working for the first 2 hits but on the 3rd hit this error is coming.

const http = require('http');

const fs = require('fs')

module.exports.verifyPyeval5 = function(request, response){
    let filePath = "D:/PyEval/NewPyEvalRequests/solution.txt";  
    fs.readFile(filePath, 'utf8', function (err,data) {
       var json = JSON.parse(data);
        post_call(json,function(res){
            response.status(200)
        .json(res);
        });
    });   

};

var post_call = function(new_val,callback){
    var post_req = http.request(post_options, function(res) { 
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            callback(chunk);
        });
      });
      post_req.write(JSON.stringify(new_val));
      post_req.end();

};

var post_options = {
      host: 'acclabserv',
      port: '8080',
      path: '/generate',
      method: 'POST',
      headers: {
          'Content-Type': 'application/json'
      }
  };

Upvotes: 2

Views: 112

Answers (1)

Yash Ganatra
Yash Ganatra

Reputation: 468

I got it the issue is with callback function it gets called more then once.

var post_call = function(new_val,callback){
    var post_req = http.request(post_options, function(res) { 
        res.setEncoding('utf8');
        var str = null;
        res.on('data', function (chunk) {
            str += chunk;
        });
      res.on('end', function () {
            callback(str);
        });
      });
      post_req.write(JSON.stringify(new_val));
      post_req.end();

};

One more thing to note here I dont know the type of chuck if its an object and you want array of object in response then you can use this

var str = []; //in req.on('data') str.push(chunck)

Upvotes: 2

Related Questions