proxy.js 1.7 KB

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