How is an HTTP POST request made in node.js?

后端 未结 21 2319
南方客
南方客 2020-11-21 23:54

How can I make an outbound HTTP POST request, with data, in node.js?

相关标签:
21条回答
  • 2020-11-22 00:26

    You can also use Requestify, a really cool and simple HTTP client I wrote for nodeJS + it supports caching.

    Just do the following:

        var requestify = require('requestify');
    
        requestify.post('http://example.com', {
            hello: 'world'
        })
        .then(function(response) {
            // Get the response body (JSON parsed or jQuery object for XMLs)
            response.getBody();
        });
    
    0 讨论(0)
  • 2020-11-22 00:26

    By using request dependency.

    Simple solution :

     import request from 'request'
     var data = {
            "host":"127.1.1.1",
            "port":9008
        }
    
    request.post( baseUrl + '/peers/connect',
            {
                json: data,  // your payload data placed here
                headers: {
                    'X-Api-Key': 'dajzmj6gfuzmbfnhamsbuxivc', // if authentication needed
                    'Content-Type': 'application/json' 
                }
            }, function (error, response, body) {
                if (error) {
                    callback(error, null)
                } else {
                    callback(error, response.body)
                }
            });
    
    0 讨论(0)
  • 2020-11-22 00:27

    If you are looking for promise based HTTP requests, axios does its job nicely.

      const axios = require('axios');
    
      axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'})
          .then((response) => console.log(response))
          .catch((error) => console.log(error));
    

    OR

    await axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'})
    
    0 讨论(0)
  • 2020-11-22 00:30

    I like the simplicity of superagent (https://github.com/visionmedia/superagent). Same API on both node and browser.

    ;(async function() {
      var response = await superagent.post('http://127.0.0.1:8125/', {age: 2})
      console.log(response)
    })
    
    

    There is also node-fetch (https://www.npmjs.com/package/node-fetch), which has an API that matches fetch from the browsers - however this requires manual query string encoding, does not automatically handle content types, or so any of the other work superagent does.

    0 讨论(0)
  • 2020-11-22 00:31
    var https = require('https');
    
    
    /**
     * HOW TO Make an HTTP Call - POST
     */
    // do a POST request
    // create the JSON object
    jsonObject = JSON.stringify({
        "message" : "The web of things is approaching, let do some tests to be ready!",
        "name" : "Test message posted with node.js",
        "caption" : "Some tests with node.js",
        "link" : "http://www.youscada.com",
        "description" : "this is a description",
        "picture" : "http://youscada.com/wp-content/uploads/2012/05/logo2.png",
        "actions" : [ {
            "name" : "youSCADA",
            "link" : "http://www.youscada.com"
        } ]
    });
    
    // prepare the header
    var postheaders = {
        'Content-Type' : 'application/json',
        'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
    };
    
    // the post options
    var optionspost = {
        host : 'graph.facebook.com',
        port : 443,
        path : '/youscada/feed?access_token=your_api_key',
        method : 'POST',
        headers : postheaders
    };
    
    console.info('Options prepared:');
    console.info(optionspost);
    console.info('Do the POST call');
    
    // do the POST call
    var reqPost = https.request(optionspost, function(res) {
        console.log("statusCode: ", res.statusCode);
        // uncomment it for header details
    //  console.log("headers: ", res.headers);
    
        res.on('data', function(d) {
            console.info('POST result:\n');
            process.stdout.write(d);
            console.info('\n\nPOST completed');
        });
    });
    
    // write the json data
    reqPost.write(jsonObject);
    reqPost.end();
    reqPost.on('error', function(e) {
        console.error(e);
    });
    
    0 讨论(0)
  • 2020-11-22 00:32

    Here's an example of using node.js to make a POST request to the Google Compiler API:

    // We need this to build our post string
    var querystring = require('querystring');
    var http = require('http');
    var fs = require('fs');
    
    function PostCode(codestring) {
      // Build the post string from an object
      var post_data = querystring.stringify({
          'compilation_level' : 'ADVANCED_OPTIMIZATIONS',
          'output_format': 'json',
          'output_info': 'compiled_code',
            'warning_level' : 'QUIET',
            'js_code' : codestring
      });
    
      // An object of options to indicate where to post to
      var post_options = {
          host: 'closure-compiler.appspot.com',
          port: '80',
          path: '/compile',
          method: 'POST',
          headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Content-Length': Buffer.byteLength(post_data)
          }
      };
    
      // Set up the request
      var post_req = http.request(post_options, function(res) {
          res.setEncoding('utf8');
          res.on('data', function (chunk) {
              console.log('Response: ' + chunk);
          });
      });
    
      // post the data
      post_req.write(post_data);
      post_req.end();
    
    }
    
    // This is an async file read
    fs.readFile('LinkedList.js', 'utf-8', function (err, data) {
      if (err) {
        // If this were just a small part of the application, you would
        // want to handle this differently, maybe throwing an exception
        // for the caller to handle. Since the file is absolutely essential
        // to the program's functionality, we're going to exit with a fatal
        // error instead.
        console.log("FATAL An error occurred trying to read in the file: " + err);
        process.exit(-2);
      }
      // Make sure there's data before we post it
      if(data) {
        PostCode(data);
      }
      else {
        console.log("No data to post");
        process.exit(-1);
      }
    });
    

    I've updated the code to show how to post data from a file, instead of the hardcoded string. It uses the async fs.readFile command to achieve this, posting the actual code after a successful read. If there's an error, it is thrown, and if there's no data the process exits with a negative value to indicate failure.

    0 讨论(0)
提交回复
热议问题