proxy won't work in create-react-app and axios

Viewed 4806

I added "proxy": "http://localhost:3001" in package.json, and I run npm run start to start the client app.

then I do this with axios

axios.get('/')
    .then(resp => {
      console.log(resp)
      this.setState({
        name: resp.name
      })
    })

I open the network tab I'm seeing it calls http://localhost:3000 not the proxy, any clue? I have an express server running on 3001.

2 Answers

open the network tab I'm seeing it calls http://localhost:3000 not the proxy

That's how proxies work! The browser makes a request to localhost:3000 where your proxy server is running, which forwards the request to localhost:3001

Issue is in webpack config file,with your own starter pack just set "webpack.dev.js" as in code bellow

module.exports = merge(common, { mode: 'development', devServer: { host: 'localhost', port: 3000, open: true, historyApiFallback: true, proxy: { '/api': { target: 'http://localhost:5000', secure: false } } }, devtool: 'inline-source-maps' });

and set apropriate localhost for your server and restart dev-server. In "create-react-app" webpack config files should be on path /node_modules/react-scripts/config,make changes as in code above and restart dev-server and you should be fine. On this path are webpack.config.dev.js. //used by npm start webpack.config.prod.js //used by npm run build

Related