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

Share Improve this question asked Dec 30, 2016 at 1:48 T. MarrenT. Marren 611 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Maybe 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"
])

本文标签: