繁体   English   中英

NodeJS Http发布JSON数据

[英]NodeJS Http Post JSON Data

如何在NodeJS上通过Http Post正确发送JSON数据? 我已经检查过我发送的数据绝对是JSON,但是每次尝试通过http发布发送时,都会收到错误消息。 我无法完全看到错误,因为它是从终端返回的,即使我输出了,也太乱了,格式不正确

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

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

实际上,您可以使用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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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