Reactjs 动态获取应用程序基URL
我正在使用端点调用一个Reactjs 动态获取应用程序基URL,reactjs,Reactjs,我正在使用端点调用一个APIhttp://localhost:8080/api/something..在development模式下使用axios,现在端点部署到https://www.myapp.com/api/something,将来此端点的基本url可能会更改。那么如何动态设置基本url?您应该创建一个axios实例: const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout:
API
http://localhost:8080/api/something..在development
模式下使用axios
,现在端点部署到https://www.myapp.com/api/something
,将来此端点的基本url
可能会更改。那么如何动态设置基本url
?您应该创建一个axios实例:
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
然后您可以像这样使用实例:
const data = await instance.get("api/something..")
const instance = axios.create({
baseURL: process.env.REACT_APP_BASE_URL,
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
要设置基本url,可以使用。设置如下:
const data = await instance.get("api/something..")
const instance = axios.create({
baseURL: process.env.REACT_APP_BASE_URL,
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
对于不同的部署环境,可以创建不同的文件。例如,对于暂存环境,您可以创建一个.env.staging
文件并写入:
REACT_APP_BASE_URL=http://api.staging
对于生产环境,您可以创建一个.env.production
,并在其中写入:
REACT_APP_BASE_URL=https://api.production
什么是
基本url
?比如http://localhost:8080
这是本地url,这是https://www.myapp.com
production URL那么我是否应该每次都更改此baseURL
?我的意思是分别针对dev
模式和production
模式?@bakar\u dev No.您需要使用env变量
。再次阅读我的答案(以及链接的资源),因为我在你提交评论之前编辑了它。如果您有任何其他问题,请随时提问。我已设置了REACT\u APP\u BASE\u URL=https//www.myapp.com
,如果端点部署到其他URL,该怎么办https://www.mayapp2.com几天后?