I have a React app, which is currently on localhost 3000. The server side is being handled by a Node Express app, which is currently listening on localhost 3001.
When I run npm start, I concurrently start the two.
I realized in the useEffect code below, that I cannot relatively set the path of my Express App (called with axious, because while I am on the React app (localhost 3000), my Express App is running on 3001. Im wondering on how to implement this as a relative path, as looking forward, when I need to deploy this app, I believe this will be a situation I will run into problems, thank you.
useEffect(() => {
console.log("this is our use effect function")
//we can make our async function here
//we can call the user favourites in the db to populate our recipes
//we can also call the db to populate the items in this users fridge.
//we store our token in the local storage.
async function getUser(){
let res = await axios.get("http://localhost:3001/users/testuser")
console.log(res.data)
}
getUser()
},[])
2
Answers
This can be achieved with the help of axios config defaults. You don’t need to specify the full url instead you can just specify the particular end point that needs to serve you the response. For deployment, You need to host your backend node application in a separate server. (I suggest using Render). And react app in a separate server.
After deployment you will get a url to access the server (which will be the url of your backend)
You can also add common headers and can handle response by the use of
axios-interceptors
. Refer axiosDocs.React app can be hosted in netlify.
Remember, wherever you use axios you need to import axios from axiosConfig.js file.
Certainly! In a React application, you can use environment variables defined in a .env file to manage configuration settings.
Here’s a simple example:
Create a .env file: In the root of your React project, create a file named .env.
Access environment variables in your React code: You can use the variables in your React components or other JavaScript files.
during deployement you can change
EXPRESS_SERVER_URL
with your backend endpointif you are using websites like vercel to deploy the website it will ask for the environment variables you can update it with you .env