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

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

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

21条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 00:25

    request is now deprecated. It is recommended you use an alternative

    In no particular order and dreadfully incomplete:

    • native HTTP/S, const https = require('https');
    • node-fetch
    • axios
    • got
    • superagent
    • bent
    • make-fetch-happen
    • unfetch
    • tiny-json-http
    • needle
    • urllib

    Stats comparision Some code examples

    Original answer:

    This gets a lot easier if you use the request library.

    var request = require('request');
    
    request.post(
        'http://www.yoursite.com/formpage',
        { json: { key: 'value' } },
        function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body);
            }
        }
    );
    

    Aside from providing a nice syntax it makes json requests easy, handles oauth signing (for twitter, etc.), can do multi-part forms (e.g. for uploading files) and streaming.

    To install request use command npm install request

提交回复
热议问题