2

I am parsing my json on end but I am still receiving this error.

'use strict';
const http = require('http');
const tools = require('./tools.js');

const server = http.createServer(function(request, response) {
    console.log("received " + request.method + " request from " + request.headers.referer)

    var body = "";
    request.on('error', function(err) {
        console.log(err);
    }).on('data', function(chunk) {
        body += chunk;
    }).on('end', function() {
        console.log("body " + body);
        var data = JSON.parse(body); // trying to parse the json
        handleData(data);
    });

    tools.setHeaders(response);
    response.write('message for me');
    response.end();
});
server.listen(8569, "192.168.0.14");

console.log('Server running at 192.168.0.14 on port ' + 8569);

Data being sent from the client:

var data = JSON.stringify({
    operation: "shutdown",
    timeout: 120
});

I successfully receive the json but I am unable to parse it.

Update:

I've updated the code to include the server code in its entirety.

To be perfectly clear, using the following code:

....
}).on('end', function() {
        console.log("body " + body);
        var json = JSON.parse(body); // trying to parse the json
        handleData(json);
});

I get this:

description

However, this:

....
}).on('end', function() {
    console.log("body " + body);
    //var json = JSON.parse(body); // trying to parse the json
    //handleData(json);
});

produces this

description

stefanhorne
  • 1,619
  • 3
  • 16
  • 23
  • 1
    `JSON.parse` accepts a string that should be a valid JSON. The error you are getting means that what you are parsing isn't a valid JSON. When I use your stringified `data` variable and pass it to `JSON.parse`, it all works fine. – nem035 May 05 '16 at 22:07
  • I was trying a couple of things. I've updated my question – stefanhorne May 05 '16 at 22:07
  • 1
    Try adding a `console.log( body );` right before your call to `JSON.parse` to verify that `body` actually has what you expect it to. – Paul May 05 '16 at 22:09
  • How is this `data` getting to `request.on`? Can you please provide a [MCVE]? – OneCricketeer May 05 '16 at 22:10
  • What do you get when you print body? – Striker May 05 '16 at 22:11
  • What is `request`? Which library are you using? – rxgx May 05 '16 at 22:47
  • Request is a node request object – stefanhorne May 05 '16 at 22:51
  • 1
    What do you mean when you say `This is the output when I log body before parsing:`? That should be the exact same thing as if you log body without parsing (minus the error which will follow it, of course). – dvlsg May 05 '16 at 23:03

3 Answers3

1

Can we see the server code, please?

Here is a working end-to-end example which is (more or less) what you are attempting, I believe.

"use strict";
const http = require('http');

/********************
  Server Code
********************/
let data = {
    operation: 'shutdown',
    timeout: 120
};
const server = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify(data));
    res.end();
});
server.listen(8888);

/********************
  Client Code
********************/
let options = {
    hostname: 'localhost',
    port: 8888,
    path: '/',
    method: 'POST',
    headers: {
        'Accept': 'application/json'
    }
};
let req = http.request(options, res => {
    let buffer = '';
    res.on('data', chunk => {
        buffer += chunk;
    });
    res.on('end', () => {
        let obj = JSON.parse(buffer);
        console.log(obj);
        // do whatever else with obj
    });
});
req.on('error', err => {
    console.error('Error with request:', err);
});
req.end(); // send the request.
dvlsg
  • 5,378
  • 2
  • 29
  • 34
1

It turns out that as this is a cross-origin(cors) request, it was trying to parse the data sent in the preflighted request.

I simply had to add an if to catch this

....    
}).on('end', function() {
    if (request.method !== 'OPTIONS') {
        var data = JSON.parse(body);
        handleData(data);
    }
});

success

Further reading if you're interested: HTTP access control (CORS)

stefanhorne
  • 1,619
  • 3
  • 16
  • 23
-2

Put the identifiers in quotes.

{
    "operation": "shutdown",
    "timeout": 120
}

http://jsonlint.com/ Is a helpful resource.

Rob Wood
  • 415
  • 5
  • 11