简体   繁体   中英

How does the “proxy” field in a create-react-app's package.json work?

I have a NodeJS backend running at http://localhost:4050 , and I had configured my react application to make API calls to there. For deploying on heroku, I had to change the PORT variable in the backend to be process.env.PORT . As a result when I put the react app's build folder in the backend's server folder, the react application was still searching for localhost:4050 when I deployed to heroku and naturally failed to make calls, because heroku ran the application on an arbitrarily different port. But apparently adding the very same http://localhost:4050 as "proxy":"http://localhost:4050" in the package.json file worked. I'm really curious as to how doing that got it to work.

proxy field in package.json is used to proxy all requests from frontend domain to backend. For example, you have:

  • Backend (REST API): localhost:5000/api/user/:id
  • Frontend (React.JS app): localhost:3000/user

If you call axios.get('/api/user/123') , the browser will send this request to localhost:3000/api/user/123 , but then react dev server will peoxy it to localhost:5000/api/user/123

Please note that this is only for development environment. If you want to deploy your React.JS, there's a better way:https://blog.heroku.com/deploying-react-with-zero-configuration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM