const http = require('http');
const url = require('url');
const querystring = require('querystring');
http.createServer(function(oreq, ores) {
console.log("服务已开启");
if (oreq) {
if (oreq.url !== '/favicon.ico') {
let content = '',
postData = '';
// 封装获取参数的方法
function getParmas(oUrl) {
let oQuery = (typeof oUrl === "object") ? oUrl : url.parse(oUrl, true).query,
data = {};
for (item in oQuery) {
if (item !== 'hostname') {
if (item !== 'path') {
data[item] = oQuery[item];
}
}
}
return querystring.stringify(data);
};
// 封装发起http请求的方法
function httpRequest(options, ores) {
let datas = "";
return http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function(chunk) {
// 返回数据
datas += chunk;
});
res.on('end', function() {
ores.writeHead(200, {
"Content-Type": "application/json; charset = UTF-8",
"Access-Control-Allow-Origin": "*"
});
ores.end(datas);
})
})
};
// 数据块接收中
console.log(oreq.method.toUpperCase());
if (oreq.method.toUpperCase() === "POST") {
console.log("进入POST");
oreq.on("data", function(postDataChunk) {
postData += postDataChunk;
});
// 数据接收完毕,执行回调函数
oreq.on("end", function() {
console.log("接收完毕")
console.log(postData);
// 配置options
let oData = JSON.parse(postData);
postData = getParmas(oData);
let options = {
hostname: oData.hostname,
port: '80',
path: oData.path,
method: "POST"
};
// 发送请求
let req = httpRequest(options, ores);
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(postData); //发送请求数据
req.end();
});
} else {
let queryObj = url.parse(oreq.url, true).query;
content = getParmas(oreq.url);
let options = {
hostname: queryObj.hostname,
port: '80',
path: queryObj.path + content,
method: "GET"
};
// 发送请求
let req = httpRequest(options, ores);
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
}
}
}
}).listen(8080, '127.0.0.1');
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有