Node js Http常用请求封装

一、Node js Http常用请求封装

常用的get请求,post请求封装

requestHelper.js模块定义

内容如下:

var http = require('https');//如果是http请求引用http模块,如果是https请求引用https模块
var queryString=require('querystring');

var req = {
    //get请求封装
    get: (link, data, callback) => {
        http.get(link, data, (req, res) => {
            var html = '';
            req.on('data', data => {
                html += data;
            });
            req.on('end', () => {
                callback(html);
            });
        });
    },
    //post 请求封装
    post: (link, data, callback) => {
       //var postData = JSON.stringify(data)
 var postData = queryString.stringify(data);
        var options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                'Content-Length': Buffer.byteLength(postData)
            }
        }
        var req = http.request(link, options, (res) => {
            res.setEncoding('utf-8');
            var html = '';
            res.on('data', chun => {
                html += chun;
            });

            res.on('end', () => {
                callback(html);
            });
        });
        req.write(postData);
        req.end();
    }
}

module.exports = req;

 

 

更多:

使用webpack打包nodejs 后台端环境|NodeJs 打包后台代码

Node.Js http模块(一)-发送http请求实例

 Node.Js Path模块-文件或文件夹路径字符串操作

你可能感兴趣的:(NodeJs,nodejs,http常用请求封装)