nodejs代理服务器怎么设置?

Node.js 代理服务器实现

nodejs代理服务器怎么设置

下面我将展示如何使用Node.js创建一个功能完整的代理服务器,包含基本代理功能和可视化界面。

思路分析

1、使用Node.js的httphttps模块创建服务器

2、实现HTTP和HTTPS请求的代理转发

3、添加请求/响应日志记录功能

nodejs代理服务器怎么设置

4、创建简单的前端界面展示代理活动

最终实现代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Node.js 代理服务器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: #333;
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 10px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }
        header {
            background: #4a5568;
            color: white;
            padding: 20px;
            text-align: center;
        }
        h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        .subtitle {
            font-size: 1.2rem;
            opacity: 0.8;
        }
        .content {
            display: flex;
            flex-wrap: wrap;
            padding: 20px;
        }
        .code-section {
            flex: 1;
            min-width: 300px;
            padding: 20px;
        }
        .info-section {
            flex: 1;
            min-width: 300px;
            padding: 20px;
            background: #f7fafc;
            border-radius: 8px;
        }
        h2 {
            color: #4a5568;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }
        pre {
            background: #2d3748;
            color: #cbd5e0;
            padding: 15px;
            border-radius: 8px;
            overflow-x: auto;
            line-height: 1.5;
            margin-bottom: 20px;
        }
        code {
            font-family: 'Fira Code', monospace;
            font-size: 0.9rem;
        }
        .highlight {
            color: #ff6b6b;
        }
        .logs {
            background: #2d3748;
            color: #cbd5e0;
            padding: 15px;
            border-radius: 8px;
            height: 300px;
            overflow-y: auto;
            margin-top: 20px;
        }
        .log-entry {
            margin-bottom: 8px;
            padding-bottom: 8px;
            border-bottom: 1px solid #4a5568;
        }
        .timestamp {
            color: #68d391;
            margin-right: 10px;
        }
        .method {
            color: #f6e05e;
            font-weight: bold;
        }
        .url {
            color: #63b3ed;
        }
        .status {
            color: #f6ad55;
        }
        .btn {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            margin-top: 15px;
            transition: background 0.3s;
        }
        .btn:hover {
            background: #5a67d8;
        }
        .instructions {
            margin-top: 20px;
        }
        .instructions li {
            margin-bottom: 10px;
            line-height: 1.5;
        }
        footer {
            text-align: center;
            padding: 20px;
            color: #718096;
            font-size: 0.9rem;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>Node.js 代理服务器</h1>
            <p class="subtitle">轻松实现请求转发与监控</p>
        </header>
        
        <div class="content">
            <div class="code-section">
                <h2>服务器代码</h2>
                <pre><code>const http = require('http');
const https = require('https');
const url = require('url');
const fs = require('fs');
// 创建HTTP代理服务器
const proxy = http.createServer((clientReq, clientRes) => {
    const parsedUrl = url.parse(clientReq.url);
    const options = {
        hostname: parsedUrl.hostname,
        port: parsedUrl.port || 80,
        path: parsedUrl.path,
        method: clientReq.method,
        headers: clientReq.headers
    };
    // 记录请求日志
    logRequest(clientReq);
    const proxyReq = http.request(options, (proxyRes) => {
        // 记录响应日志
        logResponse(clientReq, proxyRes);
        
        clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
        proxyRes.pipe(clientRes);
    });
    proxyReq.on('error', (err) => {
        console.error('代理请求错误:', err);
        clientRes.writeHead(500);
        clientRes.end('代理服务器错误');
    });
    clientReq.pipe(proxyReq);
});
// HTTPS代理处理
proxy.on('connect', (req, clientSocket, head) => {
    const parsedUrl = url.parse(https://${req.url});
    const serverSocket = net.connect(parsedUrl.port || 443, parsedUrl.hostname, () => {
        clientSocket.write('HTTP/1.1 200 Connection Established
');
        serverSocket.write(head);
        serverSocket.pipe(clientSocket);
        clientSocket.pipe(serverSocket);
    });
    
    serverSocket.on('error', (err) => {
        console.error('HTTPS代理错误:', err);
        clientSocket.end();
    });
});
// 请求日志记录
function logRequest(req) {
    const timestamp = new Date().toISOString();
    const log =${timestamp} - 请求: ${req.method} ${req.url}\n;
    fs.appendFileSync('proxy.log', log);
    updateLogsDisplay(log);
}
// 响应日志记录
function logResponse(req, res) {
    const timestamp = new Date().toISOString();
    const log =${timestamp} - 响应: ${req.method} ${req.url} -> ${res.statusCode}\n;
    fs.appendFileSync('proxy.log', log);
    updateLogsDisplay(log);
}
// 启动服务器
proxy.listen(3000, () => {
    console.log('代理服务器运行在 http://localhost:3000');
});</code></pre>
                
                <button class="btn" onclick="runCode()">运行代理服务器</button>
            </div>
            
            <div class="info-section">
                <h2>代理活动监控</h2>
                <div class="logs" id="logContainer">
                    <div class="log-entry">
                        <span class="timestamp">[2023-05-15T10:30:00Z]</span>
                        <span class="method">GET</span>
                        <span class="url">http://example.com/api/data</span>
                        <span class="status">→ 200</span>
                    </div>
                    <div class="log-entry">
                        <span class="timestamp">[2023-05-15T10:31:15Z]</span>
                        <span class="method">POST</span>
                        <span class="url">http://api.example.com/user</span>
                        <span class="status">→ 201</span>
                    </div>
                    <div class="log-entry">
                        <span class="timestamp">[2023-05-15T10:32:22Z]</span>
                        <span class="method">GET</span>
                        <span class="url">https://jsonplaceholder.typicode.com/posts</span>
                        <span class="status">→ 200</span>
                    </div>
                </div>
                
                <div class="instructions">
                    <h2>使用说明</h2>
                    <ul>
                        <li>将应用程序的代理设置指向 <code>localhost:3000</code></li>
                        <li>支持HTTP和HTTPS流量转发</li>
                        <li>所有请求和响应将被记录并显示在上面</li>
                        <li>查看控制台获取更详细的错误信息</li>
                        <li>日志同时保存到 <code>proxy.log</code> 文件中</li>
                    </ul>
                </div>
            </div>
        </div>
        
        <footer>
            <p>Node.js 代理服务器示例 &copy; 2023</p>
        </footer>
    </div>
    <script>
        function runCode() {
            alert('在实际环境中,此代码需要在Node.js环境中运行,\n请将代码保存为.js文件并使用Node执行。');
        }
        
        function updateLogsDisplay(log) {
            const logContainer = document.getElementById('logContainer');
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            
            const parts = log.split(' ');
            const timestamp = parts[0] + ' ' + parts[1];
            const method = parts[3];
            const url = parts[4];
            const status = parts.length > 6 ? parts[7] : '';
            
            logEntry.innerHTML = `
                <span class="timestamp">[${timestamp}]</span>
                <span class="method">${method}</span>
                <span class="url">${url}</span>
                <span class="status">${status ? '→ ' + status : ''}</span>
            `;
            
            logContainer.prepend(logEntry);
        }
        
        // 模拟一些活动
        setInterval(() => {
            const methods = ['GET', 'POST', 'PUT', 'DELETE'];
            const urls = [
                'http://api.example.com/users',
                'https://jsonplaceholder.typicode.com/posts',
                'http://example.com/api/data',
                'https://httpbin.org/get'
            ];
            const statuses = [200, 201, 404, 500];
            
            const method = methods[Math.floor(Math.random() * methods.length)];
            const url = urls[Math.floor(Math.random() * urls.length)];
            const status = statuses[Math.floor(Math.random() * statuses.length)];
            
            const timestamp = new Date().toISOString();
            const log =${timestamp} - 响应: ${method} ${url} -> ${status}\n;
            
            updateLogsDisplay(log);
        }, 5000);
    </script>
</body>
</html>

功能说明

这个代理服务器实现包含以下功能:

1、HTTP请求代理:能够转发HTTP请求到目标服务器

nodejs代理服务器怎么设置

2、HTTPS连接处理:支持HTTPS流量的隧道代理

3、请求日志记录:记录所有经过代理的请求详情

4、响应日志记录:记录目标服务器的响应状态

5、可视化界面:提供Web界面展示代理活动

使用方法

1、将提供的HTML代码保存为index.html

2、将JavaScript代码部分保存为proxy.js

3、在终端中运行node proxy.js

4、将浏览器或应用程序的代理设置指向localhost:3000

5、打开浏览器访问http://localhost:3000 查看代理活动

这个实现展示了代理服务器的核心功能,并提供了直观的界面来监控代理活动。

文章摘自:https://idc.huochengrm.cn/fwq/15486.html

评论

精彩评论
  • 2025-09-12 07:21:08

    Node.js设置代理服务器,需使用HTTP代理模块,配置代理规则并监听相应端口。