12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- const express = require('express');
- const { createProxyMiddleware } = require('http-proxy-middleware');
- const crypto = require('crypto');
- const algorithm = 'aes-256-cbc';
- const key = crypto.randomBytes(32);
- const iv = crypto.randomBytes(16);
- // 解密函数
- function decryptData(data, key, iv) {
- const decipher = crypto.createDecipheriv(algorithm, key, iv);
- let decrypted = decipher.update(data, 'hex', 'utf8');
- decrypted += decipher.final('utf8');
- return decrypted;
- }
- // 加密函数
- function encryptData(data, key, iv) {
- const cipher = crypto.createCipheriv(algorithm, key, iv);
- let encrypted = cipher.update(data, 'utf8', 'hex');
- encrypted += cipher.final('hex');
- return encrypted;
- }
- const app = express();
- // 反向代理配置
- const proxyOptions = {
- target: 'https://api.openai.com', // OpenAI API 服务器地址
- changeOrigin: true, // 修改请求头以适应目标服务器
- pathRewrite: { '^/api': '' }
- };
- // 自定义中间件:代理前操作
- const preProxyMiddleware = (req, res, next) => {
- console.log('代理请求前操作');
- // 在这里可以执行一些操作,如记录请求信息、修改请求头等
- req.body = decryptData(req.body, key, iv);
- next();
- };
- // 自定义中间件:代理后操作
- const postProxyMiddleware = (req, res, next) => {
- console.log('代理响应后操作');
- // 在这里可以执行一些操作,如记录响应信息、修改响应数据等
- req.body = encryptData(req.body, key, iv)
- next();
- };
- // 设置代理
- app.use('/api', preProxyMiddleware, createProxyMiddleware(proxyOptions), postProxyMiddleware);
- // 启动服务器
- const PORT = process.env.PORT || 3001;
- app.listen(PORT, () => {
- console.log(`Server is running on port ${PORT}`);
- });
|