123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- const express = require('express');
- const { createProxyMiddleware } = require('http-proxy-middleware');
- const crypto = require('crypto');
- const bodyParser = require('body-parser');
- const password = '2023'
- // 加密函数
- function encrypt(text) {
- const cipher = crypto.createCipher('aes-256-cbc', password);
- let encrypted = cipher.update(text, 'utf8', 'hex');
- encrypted += cipher.final('hex');
- return encrypted;
- }
- // 解密函数
- function decrypt(encrypted) {
- const decipher = crypto.createDecipher('aes-256-cbc', password);
- let decrypted = decipher.update(encrypted, 'hex', 'utf8');
- decrypted += decipher.final('utf8');
- return decrypted;
- }
- 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.messages[0].content = decrypt(req.body.messages[0].content);
- req.body.messages[1].content = decrypt(req.body.messages[1].content);
- console.log(req.body)
- next();
- };
- // 自定义中间件:代理后操作
- const postProxyMiddleware = (req, res, next) => {
- console.log('代理响应后操作');
- // 在这里可以执行一些操作,如记录响应信息、修改响应数据等
- console.log(res.json())
- next();
- };
- // 解析 application/json 格式
- app.use(bodyParser.json());
- // 解析 application/x-www-form-urlencoded 格式
- app.use(bodyParser.urlencoded({ extended: false }));
- // 设置代理
- app.use('/api', preProxyMiddleware, createProxyMiddleware(proxyOptions), postProxyMiddleware);
- // 启动服务器
- const PORT = process.env.PORT || 3001;
- app.listen(PORT, () => {
- console.log(`Server is running on port ${PORT}`);
- });
|