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

标签 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)

可能是什么原因?

最佳答案

使用JSON.stringify而不是querystring.stringify

关于json - 向服务器发送请求时 JSON 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23810423/

相关文章:

node.js - npm 安装返回 "TypeError: Cannot convert undefined or null to object"

javascript - Azure 帐户共享访问签名

javascript - 如何使用 JavaScript 动态替换 SQL 查询的一部分

Go 语言中 JSON 嵌套结构体

Python 和 Pandas : UnicodeDecodeError: 'ascii' codec can't decode byte

node.js - Sequelize [object SequelizeModel] 保存不是函数

node.js - Mongoose 复合索引唯一 + 稀疏

json - 如何将 package.json 导入 Typescript 文件而不将其包含在编译输出中?

json - Mongoose - 无法检索快速 route 的虚拟字段

php - 类型错误 : Converting circular structure to JSON: Is there any way to ignore this warning?