title: NodeJS Http Post JSON Data
body: <p>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 </p>
  
  <pre><code>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();
  </code></pre>
  
  <p>Also tried this</p>
  
  <pre><code>// request.post(
          //     '',
          //     { form: { key: result } },
          //     function (error, response, body) {
          //         if (!error &amp;&amp; response.statusCode == 200) {
          //             console.log(body);
          //         }
          //     }
          // );
          // console.log(result);
  </code></pre>