I used create-react-app as the boilerplate for my React app.
I am using fetch to make a request to my local server
fetch("http://localhost:3000/users")
.then(function(res){
return res.json()
})
.then(function(res){
return res.data
})
Eventually when I deploy to heroku I won't be using http://localhost but rather something like https://safe-escarpment-99271.herokuapp.com/ .
Is there a way to store the API url in an environment variable
ie. fetch(API_URL)
so I can have it on Github when it's deployed but still test locally and not have to change the url back and forth.
I see
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': JSON.stringify('production'),
'API_URL': JSON.stringify('http://localhost:8080/bands')
}
}),
on many answers but that doesn't seem to be working for me. When I console.log(process.env)
the only thing that shows is NODE_ENV
and PUBLIC_URL
Maybe this will work for you:
const url = (process.env.NODE_ENV === 'development')
? 'http://localhost:8080/bands/'
: 'https://<your-app>.herokuapp.com/bands/';
On heroku default NODE_ENV=production: https://devcenter.heroku.com/changelog-items/688
Try using EnvironmentPlugin :
new webpack.EnvironmentPlugin([
"NODE_ENV",
"API_URL"
])
You have to prepend a name of every new environmental variable with REACT_APP_
. In your case it would be REACT_APP_API_URL
.
The reason behind it is that create-react-app ignores all custom environmental variables if they don't start with REACT_APP_
( NODE_ENV
and PUBLIC_URL
are exceptions).
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.