create-react-app无法与代理一起使用

Jen*_*Mok 5 javascript node.js reactjs create-react-app

我使用create-react-app引导我的react应用程序,这是在package.json中完成的

"proxy":"http://localhost:3001"因为我的api服务器在3001上运行,但是我使用axios发出请求,它仍然指向端口3000,有什么线索吗?重新启动了我的应用几次,结果还是一样。

xar*_*rgr 7

在你的 package.json 添加:

"proxy": "http://localhost:3001",
Run Code Online (Sandbox Code Playgroud)

请重新启动您的服务器(后端应用程序)和前端(创建 React 应用程序)

确保您的 axios 发布请求如下所示:

axios.post("/auth/register", userData)
     .then(res => console.log(res.data));
Run Code Online (Sandbox Code Playgroud)

上面的这个例子来自我的环境并且也有效。请注意,代理仅适用于开发模式

确保您的代码在代理和 axios 中的 url 中具有正确的斜杠同时发布


小智 -4

尝试这个:

{
  "proxy": {
    "/api/foo": {
      "target": "your url" ,
      "changeOrigin": true
     },
    "/api/bar": {
      "target": "another url",
      "changeOrigin": true
     },
   }
}
Run Code Online (Sandbox Code Playgroud)