how to send a https request in nodejs

2016-09-27 00:20:44

Steps to send a https request to a rest service in Node js

  • a)use request
var request = require('request');
var options = {
    url:'https://abc.example.com.cn/In/index.php?m=Info&a=Address',
    headers: {
        'User-Agent': 'request'
    },
    rejectUnauthorized: false
};
function callback(error, response, body) {
    if (!error && response.statusCode == 200) {
        var info = JSON.parse(body);
        console.log(info);
    }else{
        console.log(error);
    }
}
request(options, callback);
  • b)use https
var https = require('https');
        var options = {
            host: 'abc.example.com.cn',
            port: 443,
            path: '/In/index.php?m=Info&a=Address',
            method: 'GET',
            rejectUnauthorized: false
            };
        var req = https.request(options, function(res) {
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
        console.log('BODY: ' + chunk);
        });
        });
        req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
        });
        // write data to request body
        req.write('data\n');
        req.write('data\n');
        req.end();    

您的鼓励是我写作最大的动力

俗话说,投资效率是最好的投资。 如果您感觉我的文章质量不错,读后收获很大,预计能为您提高 10% 的工作效率,不妨小额捐助我一下,让我有动力继续写出更多好文章。