我有部署环境和不同的域(test1-site.com, test2-site.com)。
我希望根据我的应用程序所处的环境动态设置baseURL。
const axiosInstance = axios.create({
baseURL: URL,
headers: {
'Content-Type': 'application/json',
accept: 'application/json',
},
});
我试着用比特桶和变量来做这件事,并得到这个过程。羡慕,但这不起作用。现在我正在寻找一种不同的方法。如何在没有坏代码的情况下做到这一点?
提前谢谢你。
window.location.origin
返回路径名之前的所有内容。所以如果你现在打开控制台(F12)并输入它,你会得到'https://stackoverflow.com'
From axios doc:
// `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.
baseURL: 'https://some-domain.com/api/',
所以你可以给url加上前缀或者只留下一个空斜杠:
const axiosInstance = axios.create({
baseURL: 'api/',
headers: {
'Content-Type': 'application/json',
accept: 'application/json',
},
});