如何使用 Vercel 设置代理

rid*_*nsb 6 proxy vercel

我的 API 它在另一个域下运行..并且我正在尝试使用 Vercel 配置代理..

它正在向应用程序发出请求,/api/test.json所以我尝试...在 vercel 配置上

"redirects": [
        {
            "source": "/api/test.json",
            "destination": "https://myapi.com/test.json",
        }
    ],
    "rewrites": [
        {
            "source": "/(.*)",
            "destination": "/index.html"
        }
    ]
Run Code Online (Sandbox Code Playgroud)

我收到了 404/api/test.json

Huỳ*_*yễn 5

使用通配符路径匹配 :path*语法:

\n
// in vercel.json:\n// for example proxying /api/ \xe2\x86\x92 https://backend-endpoint/\n\n{\n  "rewrites": [\n    {\n      "source": "/api/:path*",\n      "destination": "https://backend-endpoint/:path*"\n    },\n    {\n      "source": "/api/:path*/",\n      "destination": "https://backend-endpoint/:path*/"\n    }\n  ]\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

注意: 您需要如上所述的数组下两个非常相同的对象rewrites才能正常工作文档中的示例只是不带尾部斜杠的示例,它不会转换(例如) /api/auth/login/https://backend-endpoint/auth/login/,该示例只能转换/api/auth/loginhttps://backend-endpoint/auth/login(不带尾部斜杠/

\n

(我花了一天时间才意识到尾部斜杠/实际上非常重要)

\n


Ber*_*gur 4

只需使用重写即可

"rewrites": [
    {
        "source": "/api/test.json",
        "destination": "https://myapi.com/test.json",
    }
]
Run Code Online (Sandbox Code Playgroud)

然后在你的应用程序中

httpAgent
  .get('/api/test.json)
  .then(res => { console.log(res) })
Run Code Online (Sandbox Code Playgroud)