为什么React应用程序中没有webpack-dev-server代理API调用?返回404

问题描述 投票:0回答:1

我正在构建一个具有Express / Node连接的Postgres数据库的全栈React应用程序。我没有使用create-react-app。为了测试API调用,我使用axios在componentDidMount()中调用API。服务器在端口3000上运行,而React应用程序在端口8080上运行。我已经在Postman中测试了/users端点,以确保它可以正常工作。

componentDidMount() {
    // failing config for webpack dev server:
  axios.get('/api/users')
  .then((response) => {
    console.log(response)
  })
  .catch((err) => {
    console.log(err);
    console.log(err.response)
  })
  // fails:
  // axios.get('/users')
  // .then((response) => {
  //   console.log(response)
  // })
  // .catch((err) => {
  //   console.log(err);
  //   console.log(err.response)
  // })

  // works fine:
  // axios.get('http://localhost:3000/users')
  // .then((response) => {
  //   console.log(response)
  // })
  // .catch((err) => {
  //   console.log(err)
  // })
}

请注意,直接调用localhost:3000是可行的,但是我希望能够调用/users为生产环境做准备。因此,我在webpack.config.js文件中添加了以下内容:

  devServer: {
 contentBase: __dirname,
 hot: true,
 historyApiFallback: true,
 open: true,
 proxy: {
  '/api': 'http://localhost:3000',
  changeOrigin: true
  }
}

运行webpack-dev-server时是否需要添加其他一些用于代理API的调用?从我看到的教程中,在webpack.config.js中具有代理配置就足够了,但是我只得到404。

提前感谢。

node.js reactjs express axios webpack-dev-server
1个回答
0
投票

至少对我来说,该解决方案最终使用了可动态确定要指向的URL的react环境变量。我遵循了本教程:https://medium.com/@trekinbami/using-environment-variables-in-react-6b0a99d83cf5。只需将您的dev env指向localhost,然后将服务器上的任何端口指向。

© www.soinside.com 2019 - 2024. All rights reserved.