【问题标题】:NodeJS Http Post JSON DataNodeJS Http Post JSON 数据
【发布时间】:2017-11-06 00:20:46
【问题描述】:

如何在 NodeJS 上通过 Http Post 正确发送 JSON 数据?我已经检查过我发送的数据肯定是 JSON,但是每次我尝试通过 http post 发送时,它都会收到一个错误。我无法准确看到从终端返回的错误,即使我输出,它也太乱了,格式不正确

var options = {
  hostname: 'www.postcatcher.in',
  port: 80,
  path: '/catchers/5531b7faacde130300002495',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  }
};
var req = http.request(options, function(res) {
  console.log('Status: ' + res.statusCode);
  console.log('Headers: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (body) {
    console.log('Body: ' + body);
    fs.writeFile("/var/www/node/test.txt", body, function(err) {
      if(err) {
        return console.log(err);
      }
      console.log("The file was saved!");
    }); 
  });
});
req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('{"string": result}');  ///RESULT HERE IS A JSON
req.end();

也试过了

// request.post(
        //     '',
        //     { form: { key: result } },
        //     function (error, response, body) {
        //         if (!error && response.statusCode == 200) {
        //             console.log(body);
        //         }
        //     }
        // );
        // console.log(result);

【问题讨论】:

  • 你能在这里发布那个“混乱”的错误吗?它可能对其他人非常可读
  • @Салман 问题是,我使用 laravel,所以消息包含很多不相关的信息,并且由于某种原因它不完整。我可以用 PYTHON 轻松做到这一点>。
  • @Салман 我怀疑我的结果是一个对象

标签: javascript jquery ajax json node.js


【解决方案1】:

result 没有被插值。

这似乎工作正常..

http = require('http');
fs = require('fs');

var options = {
    hostname: 'www.postcatcher.in',
      port: 80,
      path: '/catchers/5531b7faacde130300002495',
      method: 'POST',
      headers: {
              'Content-Type': 'application/json',
          }
        };
var req = http.request(options, function(res) {
  console.log('Status: ' + res.statusCode);
  console.log('Headers: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (body) {
    console.log('Body: ' + body);
    fs.writeFile("test.txt", body, function(err) {
    if(err) {
        return console.log(err);
    }
              console.log("The file was saved!");
    }); 
  });
});
req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});
// write data to request body
// req.write('{"string": result}');  ///RESULT HERE IS A JSON

result = '{ "hello": "json" }';
req.write('{"string": '+result+'}');

req.end();

结果:

$ node 29712051.js 
Status: 201
Headers: {"server":"Cowboy","date":"Sat, 18 Apr 2015 04:23:52 GMT","connection":"keep-alive","x-powered-by":"Express","content-type":"text/plain","content-length":"7","set-cookie":["connect.sid=0eGSTYI2RWf5ZTkpDZ0IumOD.OrcIJ53vFcOiQSdEbWz0ETQ9n50JBnXyZRjrSyFIdwE; path=/; expires=Sat, 18 Apr 2015 08:23:53 GMT; httpOnly"],"x-response-time":"6ms","via":"1.1 vegur"}
Body: Created
The file was saved!
$ cat test.txt
Created

【讨论】:

    【解决方案2】:

    实际上,你可以使用 JSON.stringify(result) 来代替 '{"string": '+result+'}':

    http = require('http');
    fs = require('fs');
    
    var options = {
        hostname: 'www.postcatcher.in',
        port: 80,
        path: '/catchers/5531b7faacde130300002495',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    };
    var req = http.request(options, function(res) {
        console.log('Status: ' + res.statusCode);
        console.log('Headers: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (body) {
            console.log('Body: ' + body);
            fs.writeFile("test.txt", body, function(err) {
                if(err) {
                    return console.log(err);
               }
                console.log("The file was saved!");
            });
        });
    });
    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });
    // write data to request body
    // req.write('{"string": result}');  ///RESULT HERE IS A JSON
    //
    result = JSON.stringify({ hello: "json" });
    req.write('{"string": '+result+'}');
    //
    req.end();
    

    【讨论】:

      猜你喜欢
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 2016-02-13
      • 2014-03-01
      • 2013-12-23
      • 2019-09-14
      • 1970-01-01
      • 2016-07-09
      相关资源
      最近更新 更多