NodeJS调用第三方RestAPI的实现

本文介绍了如何使用Node.js中的http和https模块进行GET和POST请求,并提供了安全的HTTPS请求实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

var http = require('http'),
    https = require('https'),
    Q = require('Q');




var util = {
    /**
     * HOW TO Make an HTTP Call - GET
     *
     *  options for GET
     *  var optionsget = {
     *      hostname : 'api.t.sina.com.cn',
     *      path : '//provinces.json' // the rest of the url with parameters if needed
     *  };
     */
    get : function(optionsget){
        return this.request(optionsget,'GET',null,false);
    },
    post : function(optionspost,jsonObject){
        return this.request(optionspost,'POST',jsonObject,false);
    },
    /**
     * HOW TO Make an HTTPs Call - GET
     *
     *  options for GET
     *  var optionsget = {
     *      hostname : 'graph.facebook.com',
     *      path : '/youscada' // the rest of the url with parameters if needed
     *  };
     */
    secureGet : function(optionsget){
        return this.request(optionsget,'GET',null,true);
    },
    /**
     * HOW TO Make an HTTPs Call - POST
     *
     *  options for POST
     *  var optionspost = {
     *      hostname : 'graph.facebook.com',
     *      path : '/youscada/feed?access_token=your_api_key'
     *  };
     */
    securePost : function(optionspost,jsonObject){
        return this.request(optionspost,'POST',jsonObject,true);
    },
    /**
     *  var options = {
     *      hostname : 'graph.facebook.com',
     *      path : '/youscada/feed?access_token=your_api_key'
     *  }
     */
    request : function(options,method,jsonObject,isSecure){
        if(!(options && options.hostname && options.path)){
            throw new Error('Omit property : "hostname" or "path".');
        }

        options.method = method || 'GET';
        options.port = options.port || 80;

        if(Object.prototype.toString.call(jsonObject) === '[object Object]'){
            jsonObject = JSON.stringify(jsonObject);
            var postheaders = {
                'Content-Type' : 'application/json',
                'Content-Length' : Buffer.byteLength(jsonObject, 'utf8')
            };
            options.headers = postheaders;
        }

        var protocal = http;

        if(isSecure){
            options.port = 443;
            protocal = https;
        }

        var deferred = Q.defer(); 
        var body = "";
        // do the POST call
        var request = protocal.request(options, function(res) {
         
            res.on('data', function(trunk) {
                body += trunk;
            }).on('end',function(){
                deferred.resolve(body);
            }).on('errer',function(err){
                deferred.reject(err);
            });
        });
         
        // write the json data
        if(options.method === 'POST'){
            request.write(jsonObject);
        }
        
        request.end();
        request.on('error', function(e) {
            deferred.reject(e);
        });

        return deferred.promise;
    }

};

module.exports = util;

 

……

router.get('/rest', function(req, res,next) {
    var promise = restUtil.get({
        hostname : "api.t.sina.com.cn",
        path : "/provinces.json"
    });

    promise.then(function(data){
        res.send(data);
    },function(err){
        next(err);
    });
});

……

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值