[英]how to use different IP address for development and production with react and axios
I am building an app using react & django rest framework.I can access all of data via axios url (127.0.0.1:8000).我正在使用 react & django rest framework 构建一个应用程序。我可以通过 axios url (127.0.0.1:8000) 访问所有数据。 But when i deploy it to azure for production then the axios ip needs to change by azure container ip for requesting to the url.
但是当我将它部署到 azure 进行生产时,axios ip 需要通过 azure 容器 ip 更改以请求 url。 What is the best way to do this for production?
在生产中执行此操作的最佳方法是什么?
You can use environment variables by creating a .env
file.您可以通过创建
.env
文件来使用环境变量。 You can have a .env.development
file for development and a .env.production
file for production.你可以有一个
.env.development
发展文件和.env.production
生产文件。
When you are developing on your machine with npm start
or yarn start
, it will use the .env.development
file in your application.当您使用
npm start
或yarn start
在您的机器上进行开发yarn start
,它将在您的应用程序中使用.env.development
文件。
Note: You need to restart the development server after changing .env files for your changes to take effect during development.注意:您需要在更改 .env 文件后重新启动开发服务器,您的更改才能在开发过程中生效。
When you build for production with npm build
or yarn build
, it will use the .env.production
file.当您使用
npm build
或yarn build
build 为生产yarn build
,它将使用.env.production
文件。
.env.development .env.development
REACT_APP_AXIOS_URL="127.0.0.1:8000"
.env.production .env.生产
REACT_APP_AXIOS_URL="http://yourapi.com"
Then your application code only needs to reference these variables through process.env
.那么你的应用程序代码只需要通过
process.env
引用这些变量。
axios.get(process.env.REACT_APP_AXIOS_URL)
You can use config
for this purpose.您可以为此目的使用
config
。 It will create multiple configuration files which are loaded according to the application environment.它将创建多个根据应用环境加载的配置文件。 In your scenario, you need to install
config
using:在您的场景中,您需要使用以下命令安装
config
:
npm i config
After that create a config
folder in your project root.之后在您的项目根目录中创建一个
config
文件夹。 Create two files as default.json
and production.json
.创建两个文件作为
default.json
和production.json
。 Now you can create the JSON
file like this with different value for both files/environments:现在,您可以为两个文件/环境创建具有不同值的
JSON
文件:
{
serverURL: "localhost:3000"
}
And then use variable like:然后使用变量,如:
const config = require('config').default;
const url = config.get('serverURL');
Pass this url
variable to axios
while requesting.请求时将此
url
变量传递给axios
。 And it will automatically choose the IP
depending on the environment set.它会根据环境设置自动选择
IP
。 When you create a react.js
app build, it sets the environment to production.当您创建
react.js
应用程序构建时,它会将环境设置为生产。 Hope this will help you.希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.