如何代理 API REST 调用:(FE 托管在 Netlify 上)?

How to proxy API REST calls : (FE hosted on Netlify)?

当我要 post 调用时,它在本地工作正常,我可以使用 netlify 进行访问,但是一旦我从 Netlify 托管前端应用程序, POST代理正在设置为 netlify URL

主持 URL : https://deploy-preview-14--hungry-lovelace-df4f46.netlify.app/login

我们点击“注册”,然后点击“注册”,然后我看到 POST 方法将会 https:///abc/register

我需要它去哪里 https://xyztrial.com/register

在本地,我通过在 Package.json

中添加 Proxy: 'xyztrial.com.com' 使其工作

但是一旦我托管了它,我就无法 post 调用,我该怎么办?

已添加与上述相同的屏幕截图URL可以在线完成。

因此我收到 404 错误页面未找到

您有两个选择:

  1. 您使用 NODE_ENV env 变量将基础 URL 从 dev 切换到 prod,并在 api 调用中使用它:
const baseURL = process.env.NODE_ENV === "development" ? "localhost:5000" : "https://nameofyourapp.herokuapp.com" 

const endpoint = "/api/v1/get-posts"

fetch(baseURL + endpoint)
... 
...

这样你就不需要在开发期间在 package.json 中进行代理,它会在生产中自动切换到你的后端 URL。

  1. 使用 Netlify 代理:

Proxy to another service Similar to how you can rewrite paths like /* to /index.html, you can also set up rules to let parts of your site proxy to external services. Let’s say you need to communicate from a single-page app with an API on https://api.example.com that doesn’t support CORS requests. The following rule will let you use /api/ from your JavaScript client:

/api/* https://api.example.com/:splat 200

Now all requests to /api/... will be proxied through to https://api.example.com straight from our CDN servers without an additional connection from the browser. If the API supports standard HTTP caching mechanisms like ETags or Last-Modified headers, the responses will even get cached by our CDN nodes.

https://docs.netlify.com/routing/redirects/rewrites-proxies/#proxy-to-another-service

请记住启用 CORS 并将您的 netlify 来源放置在您的 heroku 服务器上。