0

I am looking to send a request to a server running on localhost and process its' response and reply back to the user.

        var post_data = qs.stringify({
            'parameter':'some value'
        });

        var post_options = {
            uri: 'http://localhost:9000',

            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': Buffer.byteLength(post_data)
            }
        };

        var post_req = request(post_options,function(error,response,body){
            response.setEncoding('utf-8');
            if(response.statusCode==200)
            {
                console.log(body);
                var resp_data = JSON.parse(body);
                var result = validate(resp_data,expected_output);
                res.setHeader('Access-Control-Allow-Origin','*');
                res.writeHead(200,{"Content-Type":"application/json"});
                res.write(JSON.stringify(result));
                res.end();
            }
        });
        post_req.write(post_data);
        post_req.end();

However, the 'body' parameter in the call back function of 'post_req' is undefined even though server running on localhost:9000 returns a response. On checking the 'error' parameter, it shows 'Error: Parse Error'. Help me out.

Vignesh A
  • 11
  • 4

2 Answers2

0

Are you passing JSON.parse(body) valid JSON? If not, it will give you that error.

Have a look at this question if you are passing it seemingly valid JSON. It could be that you're passing it as an object or array.

rotarydial
  • 2,181
  • 2
  • 23
  • 27
  • Actually, the 'response' parameter is itself undefined. In the line response.setEncoding('utf-8'), I am getting an error TypeError: Cannot read property 'setEncoding' of undefined – Vignesh A Nov 14 '17 at 07:06
0

I have found the fix!

It was my back end python server running at http://localhost:9000 that has been sending out junky responses.

Solution for fixing my python server found at Python's BaseHTTPServer returns junky responses

Vignesh A
  • 11
  • 4