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

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

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

21条回答
  •  难免孤独
    2020-11-22 00:20

    Update 2020:

    I've been really enjoying phin - The ultra-lightweight Node.js HTTP client

    It can be used in two different ways. One with Promises (Async/Await) and the other with traditional callback styles.

    Install via: npm i phin

    Straight from it's README with await:

    const p = require('phin')
    
    await p({
        url: 'https://ethanent.me',
        method: 'POST',
        data: {
            hey: 'hi'
        }
    })
    


    Unpromisifed (callback) style:

    const p = require('phin').unpromisified
    
    p('https://ethanent.me', (err, res) => {
        if (!err) console.log(res.body)
    })
    

    As of 2015 there are now a wide variety of different libraries that can accomplish this with minimal coding. I much prefer elegant light weight libraries for HTTP requests unless you absolutely need control of the low level HTTP stuff.

    One such library is Unirest

    To install it, use npm.
    $ npm install unirest

    And onto the Hello, World! example that everyone is accustomed to.

    var unirest = require('unirest');
    
    unirest.post('http://example.com/helloworld')
    .header('Accept', 'application/json')
    .send({ "Hello": "World!" })
    .end(function (response) {
      console.log(response.body);
    });
    


    Extra:
    A lot of people are also suggesting the use of request [ 2 ]

    It should be worth noting that behind the scenes Unirest uses the request library.

    Unirest provides methods for accessing the request object directly.

    Example:

    var Request = unirest.get('http://mockbin.com/request');
    

提交回复
热议问题