npm 安装


  • 终端输入以下命令

    npm  i -D http-proxy-middleware

根目录创建以下文件


  • api/proxy.js,注意文件目录也要一致(名为 api 的文件夹),注意根据注释修改部分配置:

    const { createProxyMiddleware } = require("http-proxy-middleware");
    
    module.exports = (req, res) => {
      let target = "";
    
      // 代理目标地址
      // 这里使用 backend 主要用于区分 vercel serverless 的 api 路径
      // xxxxx 替换为你跨域请求的服务器 如: http://baidu.com
      if (req.url.startsWith("/backend")) {
        target = "xxxxx";
      }
    
      // 创建代理对象并转发请求
      createProxyMiddleware({
        target,
        changeOrigin: true,
        pathRewrite: {
          // 通过路径重写,去除请求路径中的 `/backend`
          // 例如 /backend/user/login 将被转发到 http://backend-api.com/user/login
          "^/backend/": "/",
        },
      })(req, res);
    };
  • Vercel.json

    {
      "rewrites": [
        {
          "source": "/backend/(.*)",
          "destination": "/api/proxy"
        }
      ]
    }
  • 根据情况,http 接口请求代码前缀记得换成/backend/

    "use strict";
    module.exports = {
      NODE_ENV: '"production"',
      API_HOST: '"/backend/"',
    };

代码提交后 Vercel 操作


1、打开项目,点击 Production
2、在部署记录里的最新部署,找到右侧的三个竖点点击
3、点击Promote to Production(推广到生产)去处理跨域
4、返回项目,在Functions中选择api/proxy.js文件


页底评论