skip to Main Content
client/
  scriptWhichMakesApiCall/
         await axios.get("http://localhost:${REACT_PORT}/api/product-category");

Doing "npm run build". REACT_PORT value is baked into build.

server/
      express which dynamically assigns itself some PORT.

What modificatoins can i make to my codebase, so that my build react app makes call to the exact port my express app is listening to?

I have hard coded the PORT number in react app.
Build it.
Also hard coded the PORT number in express. This doesn’t seem robust.

2

Answers


  1. Chosen as BEST ANSWER

    To anyone stuck on this problem.

    just use a relative URL, like '/api/product-category'.

    That way it will automatically use the same hostname and port that the page was served from. So in this way no PORT is used while building the react app.


  2. Make sure to set your express server port yourself. You can do so by adding the below code to your express server entry file:

    const port = process.env.PORT || 3000; /*set 3000 to your desired port number*/
    

    Then can use the port in your react by adding it to your axios call.

    await axios.get("http://localhost:3000/api/product-category");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search