I am developing a MERN app on my local machine.
The front end is on localhost:3000
The back end is on localhost:3003
I have in my front end code a request, like so:
axios.get('localhost:3000/comments', params)
Now, I use ngrok to expose the app, like so:
ngrok start front_end back_end
and my .yml config file looks like:
tunnels:
front_end:
proto: http
addr: 3000
subdomain: fakedomaintest
back_end:
proto: http
addr: 3003
subdomain: fakedomaintestback
My question was, do I have to expose the back end in a different way, or am I splitting the stack wrong?
When I expose localhost:3000 and localhost:3003, I edit the CRUD lines in the front end code to match the ngrok URL, like so:
axios.get('fakedomaintestback.ngrok.io/comments', params)
and upon accessing fakedomaintest.ngrok.io
it works....
But is there an easier way wherein I do not have to edit the CRUD lines on the front end everytime I want to use ngrok for a remote prototype?
What am I missing here?
If your app is running at localhost:3003
then your axios call should be axios.get('localhost:3003/comments', params)
To address the url switching:
You could use dotenv
to set up environment variables for your application.
https://www.npmjs.com/package/dotenv
How it would work is you would create a .env
file in the root folder of your react application containing the following:
BACKEND_HOST=localhost:3003
Then in your code you could change all your network calls to the following:
axios.get(`${process.env.BACKEND_HOST}/comments`, params)
When you want to switch to using ngrok, you can simply change the value in the .env
file.
If you happen to be using Create React App, .env
files will already be supported, but you'll have to prefix all your variables with REACT_APP
, so BACKEND_HOST
would become REACT_APP_BACKEND_HOST