我正在尝试从axios调用重定向,但window.location.href将我重定向到错误的位置。它以某种方式将目录路径插入到url中:https://my_site.com/prod/public/en/index /prod/public是我的项目所在的路径
这只会在生产服务器中发生。在开发环境和测试服务器中,一切都很好。我还发现只有在添加索引页时才会发生这种情况,例如,如果我将/en/product_name放入/en/product_name,则/en/index就会出现这种情况。
我的代码:
return axios
    .put(`/lang/` + code)
    .then(response => {
         console.log(response.data);  // en/index
         console.log(location.href);  // https://my_site.com
         window.location.href = "/" + response.data; // redirects me to: https://my_site.com/prod/public/en/index 
     })我希望转到:https://my_site.com/en/index而不是https://my_site.com/prod/public/en/index
我哪里做错了?
发布于 2019-08-09 20:27:17
The problem:
window.location.href= "/" + response.data;重定向到页面的根目录+ en/index。在本例中,根目录是/prod/public,因此这将添加到url的起始点/中。
解决方案
如果您位于不同的子目录中,则可以使用location.origin + response.data
return axios
    .put(`/lang/` + code)
    .then(response => {
         console.log(response.data);  // en/index
         console.log(location.origin);  // https://my_site.com
         var new_location = location.origin+ "/" + response.data;
         console.log('new location is:' new_location); // to test if the url here is the same as the 1 you get directed to
window.location.href = new_location;
 // redirects me to: https://my_site.com/en/index 
     })
https://stackoverflow.com/questions/57429939
复制相似问题