[英]how to set default global config axios in React JS
i want to set default config for my axios url.我想为我的 axios url 设置默认配置。 i already searching and now i have 3 page.
我已经在搜索,现在我有 3 页。 app.js, index.js and config.env.
app.js、index.js 和 config.env。 can anyone help me to correct my code so i can make global config in my JS.
任何人都可以帮助我更正我的代码,以便我可以在我的 JS 中进行全局配置。
here's my code这是我的代码
index.js index.js
import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";
import axios from 'axios';
// core components
import Admin from "layouts/Admin.js";
import Dashboard from "layouts/Dashboard.js";
require('dotenv').config()
axios.defaults.baseURL = process.env.REACT_APP_BE_URL;
//......
config.env配置.env
REACT_APP_BE_URL = 'http://localhost/url/api'
App.js应用程序.js
import React from "react";
import axios from 'axios';
require('dotenv').config()
get = () => {
const option = {
url: REACT_APP_BE_URL + '/listpeople',
method: 'POST',
data: {
"data": {
"data": "...."
},
}
};
axios(option)
.then(response => {
this.setState({
data: response.data.data,
isLoading: false,
});
console.log(response.data);
})
but with this code i cant get the REACT_APP_BE_URL in my App.js.但是使用此代码,我无法在我的 App.js 中获取 REACT_APP_BE_URL。 help me to correct my code.
帮助我更正我的代码。
if you want to access global configuration then please follow this steps:如果您想访问全局配置,请按照以下步骤操作:
- Create.env file in your project root, not under src but.env and src folder will be siblings.
在您的项目根目录中创建.env 文件,而不是在 src 下,但是 .env 和 src 文件夹将是同级的。
- Then use process.env['REACT_APP_API_URL'] or process.env.REACT_APP_API_URL
然后使用 process.env['REACT_APP_API_URL'] 或 process.env.REACT_APP_API_URL
if it does not work then please try to create fresh react app and follow these steps.如果它不起作用,请尝试创建新的反应应用程序并按照以下步骤操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.