詳解用node.js實(shí)現(xiàn)簡單的反向代理
更新時間:2017年06月26日 11:52:11 作者:JUN_API
本篇文章主要介紹了詳解用node.js實(shí)現(xiàn)簡單的反向代理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
之前用node.js實(shí)現(xiàn)簡單的反向代理,最近需要回顧,就順便發(fā)到隨筆上了
不多說直接上代碼!
const http = require('http');
const url = require('url');
const querystring = require('querystring');
http.createServer(function(oreq, ores) {
console.log("服務(wù)已開啟");
if (oreq) {
if (oreq.url !== '/favicon.ico') {
let content = '',
postData = '';
// 封裝獲取參數(shù)的方法
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);
};
// 封裝發(fā)起http請求的方法
function httpRequest(options, ores) {
let datas = "";
return http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function(chunk) {
// 返回數(shù)據(jù)
datas += chunk;
});
res.on('end', function() {
ores.writeHead(200, {
"Content-Type": "application/json; charset = UTF-8",
"Access-Control-Allow-Origin": "*"
});
ores.end(datas);
})
})
};
// 數(shù)據(jù)塊接收中
console.log(oreq.method.toUpperCase());
if (oreq.method.toUpperCase() === "POST") {
console.log("進(jìn)入POST");
oreq.on("data", function(postDataChunk) {
postData += postDataChunk;
});
// 數(shù)據(jù)接收完畢,執(zhí)行回調(diào)函數(shù)
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"
};
// 發(fā)送請求
let req = httpRequest(options, ores);
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(postData); //發(fā)送請求數(shù)據(jù)
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"
};
// 發(fā)送請求
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');
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Node.js對MongoDB數(shù)據(jù)庫實(shí)現(xiàn)模糊查詢的方法
模糊查詢是數(shù)據(jù)庫的基本操作之一,下面這篇文章主要給大家介紹了利用Node.js對MongoDB數(shù)據(jù)庫實(shí)現(xiàn)模糊查詢的方法教程,文中給出了詳細(xì)的介紹和示例代碼,對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。2017-05-05
nodejs express配置自簽名https服務(wù)器的方法
這篇文章主要介紹了nodejs express配置自簽名https服務(wù)器的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
Node4-5靜態(tài)資源服務(wù)器實(shí)戰(zhàn)以及優(yōu)化壓縮文件實(shí)例內(nèi)容
這篇文章主要介紹了Node4-5靜態(tài)資源服務(wù)器實(shí)戰(zhàn)以及優(yōu)化壓縮文件實(shí)例內(nèi)容,有需要的朋友們可以參考學(xué)習(xí)下。2019-08-08
nodejs 提示‘xxx’ 不是內(nèi)部或外部命令解決方法
本文介紹了node.js包管理工具npm安裝模塊后,無法通過命令行執(zhí)行命令,提示‘xxx’ 不是內(nèi)部或外部命令的解決方法,給需要的小伙伴參考下。2014-11-11
Nodejs下用submit提交表單提示cannot post錯誤的解決方法
這篇文章主要介紹了Nodejs下用submit提交表單提示cannot post錯誤的解決方法,非常不錯,具有參考借鑒價值,感興趣的朋友一起看看吧2016-11-11

