一、通过http
模块创建
const http = require('http');
// 创建代理服务器
const proxyServer = http.createServer((req, res) => {
// 创建向目标服务器的请求
const options = {
hostname: 'example.com', // 目标服务器的主机名
port: 80, // 目标服务器的端口号
path: req.url, // 使用原始请求的URL路径
method: req.method, // 使用原始请求的HTTP方法
headers: req.headers // 使用原始请求的HTTP头部
};
// 发送请求到目标服务器
const proxyRequest = http.request(options, (proxyResponse) => {
// 将目标服务器的响应转发给客户端
res.writeHead(proxyResponse.statusCode, proxyResponse.headers);
proxyResponse.pipe(res);
});
// 将原始请求的数据传递给目标服务器的请求
req.pipe(proxyRequest);
// 处理目标服务器的错误
proxyRequest.on('error', (error) => {
console.error('代理请求错误:', error);
res.statusCode = 500;
res.end('代理请求错误');
});
});
// 监听代理服务器的端口号
const port = 8080;
proxyServer.listen(port, () => {
console.log('代理服务器已启动,正在监听端口', port);
});
在上面的示例代码中,我们使用http
模块创建了一个代理服务器。当收到客户端的请求时,代理服务器会创建一个向目标服务器的请求,并将原始请求的数据传递给目标服务器的请求。然后,代理服务器将目标服务器的响应转发给客户端。
二、通过http、http-proxy模块创建
const http = require('http');
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});
const server = http.createServer((req, res) => {
// 在这里处理请求和响应
proxy.web(req, res, { target: 'http://example.com' });
});
server.listen(3000, () => {
console.log('Proxy server is running on port 3000');
});
使用 httpProxy.createProxyServer({})
创建了一个代理对象 proxy
。这个代理对象可以用来处理传入的 HTTP 请求,并将其转发到目标服务器。
使用 http.createServer
方法创建了一个 HTTP 服务器。在服务器的请求处理函数中,通过 proxy.web
方法将传入的请求 req
和响应 res
转发到目标服务器。{ target: 'http://example.com' }
是一个选项对象,指定了目标服务器的地址。
使用 server.listen
方法指定服务器监听的端口号,并在回调函数中打印出服务器已经启动的提示信息。文章来源:https://uudwc.com/A/yAPRy
这段代码创建了一个简单的代理服务器,监听在本地的 3000 端口,当有请求到达时,会将请求转发到 http://example.com
这个目标服务器上。你可以根据自己的需求修改目标服务器的地址和代理服务器监听的端口号文章来源地址https://uudwc.com/A/yAPRy