代理,也称网络代理,是一种特殊网络服务,允许一个终端通过代理服务与另一个终端进行非直接的连接,这样利于安全和防止被攻击。
代理服务器,就是代理网络用户去获取网络信息,就是信息的中转,负责转发。
代理又分 正向代理 和 反向代理:
正向代理:帮助局域网内的用户访问外面的服务。
反向代理:帮助外面的用户访问局域网内部的服务。
一、安装 http-proxy
npm install http-proxy --save
二、代理本地服务
const http = require('http');
const httpProxy = require('http-proxy');
//创建一个代理服务
const proxy = httpProxy.createProxyServer();
//创建http服务器并监听8888端口
let server = http.createServer(function (req, res) {
//将用户的请求转发到本地9999端口上
proxy.web(req, res, {
target: 'http://localhost:9999'
});
//监听代理服务错误
proxy.on('error', function (err) {
console.log(err);
});
});
server.listen(8888, '0.0.0.0');
9999端口服务代码: