nodejs将http.request请求封装成模块

nodejs将http.request请求封装成模块

服务端代码
server.js:

const express = require('express');
const urlencoded = express.urlencoded;
const json = express.json;
const app = express();

app.use(json());
app.use(urlencoded({
     extended:false}));

app.post('/', function(req, res){
     
	console.log(req.body);
	res.json({
      msg: req.body.msg });
});

app.listen(8080, function(){
     
	console.log('当前进程', process.pid);
})

将http.request请求封装成模块
requestHttp.js:

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

module.exports = function(options, postData, cb){
     
    var postData = querystring.stringify(postData)
    var req = http.request(options, function(res) {
     
        res.setEncoding('utf8');
        var str = "";
        res.on('data', function (chunk) {
     
            str+=chunk;
        });
        res.on('end', function () {
     
            cb(null,str);
        });
    });
    req.on('error', function(e) {
     
        cb(e.message);
    });
    req.write(postData);
    req.end();
};

使用案例
test.js:

const http = require('http');
const requestHttp = require('./requestHttp');
const postData = {
     
  'msg' : 'Hello World!'
};
const options = {
     
  hostname: 'localhost',
  port: 8080,
  path: '/',
  method: 'POST',
  headers: {
     
    'Content-Type': 'application/x-www-form-urlencoded',
  }
};

requestHttp(options, postData, function(err, res){
     
	if(err){
     
		console.log(err);
	}
	console.log(res);
	//{"msg":"Hello World!"}
})

你可能感兴趣的:(nodejs,nodejs,js,javascript,node.js)