使用nodeJs的express+axios+cors做代理
前端在请求后端时通常会遇到跨域cors问题,如果只在本地开发可以通过webpack或vite的proxy设置。但如果需要在线上或者其他地方绕过跨域,可以使用代理的方法。
1. 创建文件夹
并创建以下文件
package.json
            
            
              js
              
              
            
          
          {
  "name": "proxy",
  "version": "1.0.0",
  "description": "",
  "main": "proxy.js",
  "scripts": {
    "start": "node index.js",
    "start:pm2": "pm2 start index.js --name your-app-name"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^1.8.4",
    "cors": "^2.8.5",
    "express": "^3.5.3"
  }
}
        index.js
            
            
              js
              
              
            
          
          const express = require("express");
const axios = require("axios");
const cors = require("cors");
// 创建 Express 应用
const app = express();
// 使用中间件解析 JSON 和 URL 编码的请求体
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 使用 CORS 中间件,允许跨域请求,并设置 credentials 为 true
app.use(
  cors({
    origin: function (origin, callback) {
      // 允许所有来源的请求
      callback(null, true);
    },
    credentials: true, // 允许携带凭证
  })
);
// 目标地址
const TARGET_URL = "https://www.baidu.com/apis";
// 代理路由
app.use("/apis", async (req, res) => {
  try {
    // 获取客户端请求的路径和查询参数
    const path = req.path;
    const queryParams = req.query;
    // 构造目标 URL
    const targetUrl = `${TARGET_URL}${path}`;
    // 转发请求到目标地址
    const response = await axios({
      method: req.method,
      url: targetUrl,
      params: queryParams,
      headers: {
        ...req.headers,
        host: new URL(TARGET_URL).host, // 替换 Host 头为目标地址的主机名
      },
      data: req.body, // 如果是 POST/PUT 请求,转发请求体
    });
    // 将目标服务器的响应返回给客户端
    res.status(response.status).send(response.data);
  } catch (error) {
    // 处理错误
    if (error.response) {
      // 如果目标服务器返回了错误响应
      res.status(error.response.status).send(error.response.data);
    } else {
      // 其他错误
      res.status(500).send({ error: "Proxy request failed" });
    }
  }
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Proxy server is running on port ${PORT}`);
});
        2. 执行npm i
3. 执行
提供node或PM2两种执行方式
- npm run start
 - npm run start:pm2
 
之后所有访问 http://localhost:3000/apis的请求将被代理到https://www.baidu.com/apis;具体可以自行配置
4. 部署线上 node 方式
- 
打开宝塔->软件商店->安装node.

 - 
创建一个文件夹,并将下面三个文件放上去

 - 
点击终端,执行
npm i

 - 
创建一个node项目,配置启动命令和端口

启动成功后访问
宝塔IP:3000/apis将会被代理到https://www.baidu.com/apis 
4. 部署线上 pm2 方式
- 打开宝塔->软件商店->PM2管理器

 - 同上
 - 同上
 - 配置pm2

启动成功后访问宝塔IP:3000/apis将会被代理到https://www.baidu.com/apis