最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NodeJS Http Post JSON Data - Stack Overflow

programmeradmin2浏览0评论

How do I properly send JSON data over Http Post on NodeJS? I have checked that the data I'm sending is definitely JSON but every time I try sending over http post, it would receive an error. I cant exactly see the error as it's returning from terminal and even if I output, it's too messy, not properly formatted

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

Also tried this

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

How do I properly send JSON data over Http Post on NodeJS? I have checked that the data I'm sending is definitely JSON but every time I try sending over http post, it would receive an error. I cant exactly see the error as it's returning from terminal and even if I output, it's too messy, not properly formatted

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

Also tried this

// request.post(
        //     '',
        //     { form: { key: result } },
        //     function (error, response, body) {
        //         if (!error && response.statusCode == 200) {
        //             console.log(body);
        //         }
        //     }
        // );
        // console.log(result);
Share Improve this question edited Nov 5, 2017 at 16:20 Shiladitya 12.2k17 gold badges28 silver badges42 bronze badges asked Apr 18, 2015 at 1:57 JohnDotOwlJohnDotOwl 3,75514 gold badges58 silver badges102 bronze badges 3
  • Can you post that "messy" error here? Its might be very much readable to others – Salman Commented Apr 18, 2015 at 7:36
  • @Салман problem is, i use laravel so the message contains alot of unrelevent info and it's not full for some reason. I can do this just easily with PYTHON >.< Still trying it out , the answer below doesnt work "yet" – JohnDotOwl Commented Apr 18, 2015 at 7:37
  • @Салман I suspect my result is a object – JohnDotOwl Commented Apr 18, 2015 at 7:40
Add a comment  | 

2 Answers 2

Reset to default 12

result is not being interpolated.

this seems to work correctly..

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

result:

$ 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

actually, u can use JSON.stringify(result) to instead '{"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();
发布评论

评论列表(0)

  1. 暂无评论