前端代理接口报错问题排查

69 阅读3分钟

需求描述:

最近在看一个开源项目,想前端本地调试,调用它线上地址:https://****.ai/apps

实现方案:

前端直接配置,代理它线上地址

实现:

前端 next.config.ts 配置:

const nextConfig: NextConfig = {
  // ...
  async rewrites() {
    return [
      {
        source: '/console/api/:path*',
        destination: `https://cloud.dify.ai/console/api/:path*`,
      }
    ]
  }
}

代理的结果是 相关接口使用调用不成功;

diy1.png

理论上 真实的代理地址是:

https://cloud.dify.ai/console/api/system-features

在项目中访问 无法正常调用;

然后我通过浏览器直接访问;

通过浏览器是可以正常访问的;✅

dify2.png

问题:

浏览器可以访问,前端项目中代理时不能访问

环境:

本地网络环境是,开启了相关网络环境

最终问题确认:

Next.js 的 rewrites 代理请求没有走本地 Clash 代理。这是因为 Next.js 在服务端(Node.js 环境)执行 rewrites 时,其底层使用的是标准的 HTTP/HTTPS 客户端(如 httphttps 模块或 undici),而 这些客户端默认不会自动使用系统或本地的 HTTP/HTTPS 代理(如 Clash) ,除非显式配置

所以,我们的前端项目没有走系统代理,所以访问不了接口;

解决方案:

方案一:

使用 http-proxy-agent + 自定义 fetch (推荐用于 Next.js 13+ App Router)

但注意:rewrites 是 Next.js 内置功能,无法直接注入自定义代理逻辑。所以更可行的做法是:

不要用 rewrites 做跨域代理到需要走代理的外部 API改用 API Route(pages/api/proxy.ts)做中转,并在该路由中显式配置代理

推荐做法:用 API 路由中转 + 配置代理

  1. 删除 next.config.js 中的 rewrites
  2. 创建一个 API 路由pages/api/console/[...path].ts
// pages/api/console/[...path].ts
import { NextApiRequest, NextApiResponse } from 'next';
import { createProxyMiddleware } from 'http-proxy-middleware';
​
// 注意:http-proxy-middleware 在 Vercel 上不工作,仅适用于本地开发或自托管
const proxy = createProxyMiddleware({
  target: 'https://cloud.dify.ai',
  changeOrigin: true,
  pathRewrite: {
    '^/api/console': '/console', // 将 /api/console/foo → /console/foo
  },
  agent: process.env.NODE_ENV === 'development' 
    ? new (require('https-proxy-agent'))('http://127.0.0.1:7890')
    : undefined,
});
​
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  return new Promise((resolve, reject) => {
    (proxy as any)(req, res, (result: unknown) => {
      if (result instanceof Error) {
        reject(result);
      } else {
        resolve(result);
      }
    });
  });
}
​
export const config = {
  api: {
    bodyParser: false,
    externalResolver: true,
  },
};
  1. 安装依赖
npm install http-proxy-middleware https-proxy-agent
  1. 前端代码中将请求指向你的本地 API 路由

原来可能请求:

/console/api/workspaces

现在改为:

/api/console/api/workspaces

或者你在前端统一配置 baseURL 为 /api/console

注意事项

  • http-proxy-middlewarehttps-proxy-agent 只适用于 Node.js 环境,不能在浏览器中运行。
  • 如果你部署到 Vercel,Clash 代理不可用,这种代理方式只适合 本地开发
  • 如果你只是本地开发,也可以考虑 让 Clash 全局接管流量(TUN 模式) ,这样 Node.js 请求也会被透明代理。但不是所有 Clash 客户端都默认开启 TUN。

方案二:

替代思路:开启 Clash 的 TUN 模式(透明代理)

如果你使用的是 Clash Verge / Clash Meta 等支持 TUN 模式的客户端:

  • 开启 TUN 模式(或“增强模式”)
  • 这样所有本地应用(包括 Node.js)的网络请求都会被强制走代理
  • 此时 Next.js 的 rewrites 就能自动走 Clash,无需改代码

✅ 优点:无需改代码 ❌ 缺点:依赖客户端配置,且可能影响其他网络请求

总结

方案是否推荐说明
改用 API 路由 + https-proxy-agent✅ 强烈推荐(可控)显式指定代理,适合开发
开启 Clash TUN 模式✅ 简单快捷适合纯本地开发,但全局生效
继续用 rewrites❌ 不可行Node.js 不会自动走 HTTP 代理

个人使用的是方案二、最终接口能访问了;

不过登录之后的接口还是报错,token问题; 应该是后端接口做了限制,开发中不能直接使用线上地址;

最后还是需要自己本地启动一下它的后端服务;