NodeJS Http Post JSON Data

21,966

Solution 1

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

Solution 2

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();
Share:
21,966
CodeGuru
Author by

CodeGuru

Startups , Startups & Startups. Failure , Failure & Failure. I'm not giving up.

Updated on November 06, 2020

Comments

  • CodeGuru
    CodeGuru over 3 years

    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);
    
    • Salman
      Salman about 9 years
      Can you post that "messy" error here? Its might be very much readable to others
    • CodeGuru
      CodeGuru about 9 years
      @Салман 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"
    • CodeGuru
      CodeGuru about 9 years
      @Салман I suspect my result is a object