Nodejs通过http的get和post方式访问接口获取数据

要使用http的get和post方式访问接口获取数据,需要先安装http模块,执行如下命令:

npm install http

以下为具体封装的http的get和post的请求方式:

var http = require('http');
var qs = require('querystring');

//get方式获取内容
exports.get = function(host, port, path, data, callback) {
    var content = qs.stringify(data);
    var opt = {
        method: 'GET',
        host: host,
        port: port,
        path: path + '?' + content,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    };
    http.get(opt, function(res) {
        if(res.statusCode === 200) {
            res.on('data', function(body) {
                callback(0, body);
            });
        } else {
            callback(res.statusCode);
        }
    }).on('error',function(e) {
        callback(-1, 'Got error: ' + e.message);
    });
};

//post方式获取内容
exports.post = function(host, port, path, data, callback) {
    var content = qs.stringify(data);
    var opt = {
        method: 'POST',
        host: host,
        port: port,
        path: path,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    };
    var req = http.request(opt, function(res) {
        if(res.statusCode === 200) {
            res.on('data', function(body) {
                callback(0, body);
            });
        } else {
            callback(res.statusCode);
        }
    }).on('error',function(e) {
        callback(-1, 'Got error: ' + e.message);
    });
    req.write(content);
    req.end();
};

以下为调用方式:

var http = require('./system/http');

var data = {
    name: '123'
};

http.get('127.0.0.1', 8088, '/admin/widget.jsp', data, function(code, body) {
    console.log('code:'+code+'|\tbody:'+body);
});

http.post('127.0.0.1', 8088, '/admin/widget.jsp', data, function(code, body) {
    console.log('code:'+code+'|\tbody:'+body);
});

自此,http的模块已经完成了

感谢您的阅读,希望对您有帮助,本文版权归 #惊讶# 所有

评论 (0)