简体   繁体   中英

cors unexpected end of JSON input

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:

描述

However, this:

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

produces this

描述

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.

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

成功

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

Put the identifiers in quotes.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM