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

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

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

21条回答
  •  春和景丽
    2020-11-22 00:11

    You can use request library. https://www.npmjs.com/package/request

    var request = require('request');
    

    To post JSON data:

    var myJSONObject = { ... };
    request({
        url: "http://josiahchoi.com/myjson",
        method: "POST",
        json: true,   // <--Very important!!!
        body: myJSONObject
    }, function (error, response, body){
        console.log(response);
    });
    

    To post xml data:

    var myXMLText = '...........'
    request({
        url: "http://josiahchoi.com/myjson",
        method: "POST",
        headers: {
            "content-type": "application/xml",  // <--Very important!!!
        },
        body: myXMLText
    }, function (error, response, body){
        console.log(response);
    });
    

提交回复
热议问题