2

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'
      }
  };
Chandan Kumar
  • 387
  • 3
  • 13
  • why are you using this line `post_req.write(JSON.stringify(new_val));` what it is for ? – Arpit Solanki Jul 17 '17 at 13:35
  • Possible duplicate of [Error: Can't set headers after they are sent to the client](https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client) – George Jul 17 '17 at 13:53
  • **post_req.write(JSON.stringify(new_val));** This is for writing a json to the request. – Chandan Kumar Jul 18 '17 at 05:22

1 Answers1

2

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)

Yash Ganatra
  • 468
  • 2
  • 12