proxy.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const express = require('express');
  2. const { createProxyMiddleware } = require('http-proxy-middleware');
  3. const crypto = require('crypto');
  4. const bodyParser = require('body-parser');
  5. const password = '2023'
  6. // 加密函数
  7. function encrypt(text) {
  8. const cipher = crypto.createCipher('aes-256-cbc', password);
  9. let encrypted = cipher.update(text, 'utf8', 'hex');
  10. encrypted += cipher.final('hex');
  11. return encrypted;
  12. }
  13. // 解密函数
  14. function decrypt(encrypted) {
  15. const decipher = crypto.createDecipher('aes-256-cbc', password);
  16. let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  17. decrypted += decipher.final('utf8');
  18. return decrypted;
  19. }
  20. const app = express();
  21. // 反向代理配置
  22. const proxyOptions = {
  23. target: 'https://api.openai.com', // OpenAI API 服务器地址
  24. changeOrigin: true, // 修改请求头以适应目标服务器
  25. pathRewrite: { '^/api': '' }
  26. };
  27. // 自定义中间件:代理前操作
  28. const preProxyMiddleware = (req, res, next) => {
  29. console.log('代理请求前操作');
  30. // 在这里可以执行一些操作,如记录请求信息、修改请求头等
  31. req.body.messages[0].content = decrypt(req.body.messages[0].content);
  32. req.body.messages[1].content = decrypt(req.body.messages[1].content);
  33. console.log(req.body)
  34. next();
  35. };
  36. // 自定义中间件:代理后操作
  37. const postProxyMiddleware = (req, res, next) => {
  38. console.log('代理响应后操作');
  39. // 在这里可以执行一些操作,如记录响应信息、修改响应数据等
  40. console.log(res.json())
  41. next();
  42. };
  43. // 解析 application/json 格式
  44. app.use(bodyParser.json());
  45. // 解析 application/x-www-form-urlencoded 格式
  46. app.use(bodyParser.urlencoded({ extended: false }));
  47. // 设置代理
  48. app.use('/api', preProxyMiddleware, createProxyMiddleware(proxyOptions), postProxyMiddleware);
  49. // 启动服务器
  50. const PORT = process.env.PORT || 3001;
  51. app.listen(PORT, () => {
  52. console.log(`Server is running on port ${PORT}`);
  53. });