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

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

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

21条回答
  •  甜味超标
    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);
    });
    

提交回复
热议问题