向服务器发送请求时无效的JSON

时间:2014-05-22 14:57:59

标签: json node.js

我写了一个服务器,我想通过发送POST请求作为客户端进行检查。

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

我得到了下一个错误:

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)

可能是什么原因?

1 个答案:

答案 0 :(得分:1)

使用JSON.stringify而非querystring.stringify