admin管理员组文章数量:1289845
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 /.
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
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./.
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
3 Answers
Reset to default 4Maybe this will work for you:
const url = (process.env.NODE_ENV === 'development')
? 'http://localhost:8080/bands/'
: 'https://<your-app>.herokuapp./bands/';
On heroku default NODE_ENV=production: https://devcenter.heroku./changelog-items/688
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).
Try using EnvironmentPlugin:
new webpack.EnvironmentPlugin([
"NODE_ENV",
"API_URL"
])
本文标签:
版权声明:本文标题:javascript - React JS: Use environment variables to specify two API urls based on production vs development - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741405955a2376944.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论