How to post json data over http as a client

Posted on
  • From espruino htttp reference:

    var options = {
        host: 'example.com', // host name
        port: 80,            // (optional) port, defaults to 80
        path: '/',           // path sent to server
        method: 'GET',       // HTTP command sent to server (must be uppercase 'GET', 'POST', etc)
        headers: { key : value, key : value } // (optional) HTTP headers
      };
    require("http").request(options, function(res) {
    

    But where do I attach some JSON data (body/payload) to the POST request ?

  • It's passed at the end of the request like this:

    var options = {
    ...
    }
    var data = JSON.stringify({"key":"value", ...});
    require("http").request(options, function(res)  {
       ...
    }).end(data);
    
  • Make sure to add the appropriate headers when sending JSON data:

    var data = JSON.stringify({ key: "value" });
    
    const options = {
        //...
        headers: {
          "Content-Type": "application/json",
          "Content-Length": json.length
        }
    };
    
    require("http").request(options, function(res)  {
       //...
    }).end(data);
    

    I recommend attaching an error handler :)

    const req = require("http").request(/* ... */);
    req.on("error", err => console.log("Request error: " + err.message)) ;
    req.end(data);
    
  • Thanks - I'll make a note to add this to: http://www.espruino.com/Internet

    Just in case there's any interest in going the other way (handling POSTed data as a server) that one does have some example code here: http://www.espruino.com/Posting+Forms

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

How to post json data over http as a client

Posted by Avatar for user73662 @user73662

Actions