我正在使用部署在heroku中的api到我的react应用程序。为了修复 cors 错误,我在 package.json 中添加代理为
"proxy":"https://mobtech.herokuapp.com"
在调用api时,我是这样做的
const res = await axios.get('/api/user')
因此,这样做在开发中效果很好,但在部署到 netlify 后就不行了。我从 netlify 文档click阅读了官方文档,但这并没有减轻我的负担。有人可以帮我举个例子吗?
我可能迟到了,但这里是如何完成的。 Netlify 应该在你的根目录中有一个名为 __redirect 的特殊文件,你可以在那里定义你的代理
/api/* https://yourapi.domain.com/:splat 200
/* /index.html 200
然后你可以像这样调用你的api
const res = fetch('/api/user') //equivalent to https://yourapi.domain.com/user
希望这有帮助
在
_redirects
文件中添加上述行会有所帮助,但在这种情况下只是需要注意。假设您有一个 API 调用以这种方式从 React 应用写入 Express 服务器,
fetch("/api/v1/items", {method: "POST"})
.then(response => response.json()).
then(res=> console.log(res))
.catch(error => {console.log(error)});
这意味着 Express 中的端点以术语
/api
开头。
在这种情况下,请确保您的
_redirect
文件看起来像这样,
/api/* https://yoia-apis.onrender.com/api/:splat 200
/* /index.html 200
在
/api
之前应该有一个额外的术语 :splat
,因为 :splat
包含由 *
代表的实体,即在这些情况下,在 api/
之后的路线的组成部分。
如果您的@Heroku端点是这样设置的, heroku api 是:在此处输入链接描述 并获取 api 类似 const fetch=等待 axios.get(/api/users)
在React应用程序的公共文件夹中添加_redirects文件 并这样写
/api/* https://domain.herokuapp.com/api/:splat 200 /* /index.html 200
您可以使用上述答案的语法添加 _redirects 文件,但请确保 根据 netlify 文档,_redirects 文件应该位于您的根构建目录中。/ 所以你必须修改 package.json 文件中的构建命令 您可以查看此答案以获取更多参考 这里