首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >window.location.href在URL中添加路径

window.location.href在URL中添加路径
EN

Stack Overflow用户
提问于 2019-08-09 20:19:38
回答 2查看 1.1K关注 0票数 0

我正在尝试从axios调用重定向,但window.location.href将我重定向到错误的位置。它以某种方式将目录路径插入到url中:https://my_site.com/prod/public/en/index /prod/public是我的项目所在的路径

这只会在生产服务器中发生。在开发环境和测试服务器中,一切都很好。我还发现只有在添加索引页时才会发生这种情况,例如,如果我将/en/product_name放入/en/product_name,则/en/index就会出现这种情况。

我的代码:

代码语言:javascript
运行
复制
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

我哪里做错了?

EN

Stack Overflow用户

发布于 2019-08-09 20:27:17

The problem:

window.location.href= "/" + response.data;重定向到页面的根目录+ en/index。在本例中,根目录是/prod/public,因此这将添加到url的起始点/中。

解决方案

如果您位于不同的子目录中,则可以使用location.origin + response.data

代码语言:javascript
运行
复制
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 
     })

票数 2
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57429939

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档