Reputation: 1151
I'm using mern stack in a project I'm working on.
Currently I'm making requests to the rest api like so.
const { data } = await axios.get('http://localhost:5000/api/testimonials/');
The API is available at http://localhost:5000/
but when I will deploy this app that url will change.
With the current approach I have replace http://localhost:5000/
with the live url.
Instead of doing that I want to store the root url in a variable.
What is the best location to store the API root in React JS?
So I can use it in every request I make and when I have to update the url I just have to update that variable.
Upvotes: 4
Views: 5498
Reputation:
You will have to use .env file to save the root url. .env should be located in the root directory.
.env file content:
rooturl=http://yourproductiondomain.com
and you can use process on your code:
const rooturl = process.env.rooturl || 'http://localhost:5000'; // for lcoalhost.. **.env** file does not work on localhost.
const { data } = await axios.get(rooturl + '/api/testimonials/');
Upvotes: 2
Reputation: 660
You can do two things ,
storing them in env variables by creating .env file for each environment
Don't forget to prefix your names with REACT_APP_ , else it won't work
using proxy in package.json .(This is the preferred way of using api in docs)
It avoids cors error as mentioned in docs
Upvotes: 5