Or Smith
Or Smith

Reputation: 3616

Invalid JSON when sending request to server

I write a server, and I want to check it by sending a POST request as client.

var local = "./0";
var querystring = require('querystring');
var http = require('http');
var fs = require('fs');

function PostCode(u, file, s) {
    // Build the post string from an object
    var post_data = querystring.stringify({
        's' : s,
        'u': u,
        'file': file,
        'store' : 'S3'
    });

    // An object of options to indicate where to post to
    var post_options = {
        'host': 'myserver.com',
        'port': '4500',
        'path': '/save',
        'method': 'POST',
        'headers': {
            'Content-Type': 'application/json'
        }
    };

    // Set up the request
    var post_req = http.request(post_options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('Response: ' + chunk);
        });
    });

    // post the data
    post_req.write(post_data,'utf8');
    post_req.end();

}


var main = function(){
    // main code
}

if (require.main === module) {
    postt();
}

function postt(){
    var allFilesName = fs.readdirSync("./0/0/0/3/0034-5453-243");
    for (var i in allFilesName) {
     PostCode("0323-565-898", "OPT", "./0/0/0/3/0034-5453-243/s");
    }
}

and I get the next error:

Response: Error: invalid json
    at Object.exports.error (/tmp/Firver/node_modules/express/node_modules/connect/lib/utils.js:60:13)
    at IncomingMessage.<anonymous> (/tmp/Firver/node_modules/express/node_modules/connect/lib/middleware/json.js:74:71)
    at IncomingMessage.EventEmitter.emit (events.js:92:17)
    at _stream_readable.js:920:16
    at process._tickDomainCallback (node.js:459:13)

What can be the reason?

Upvotes: 1

Views: 897

Answers (1)

mscdex
mscdex

Reputation: 106736

Use JSON.stringify and not querystring.stringify.

Upvotes: 1

Related Questions