获取后端给的地址,来作为请求的根路径
获取后端给的地址,来作为请求的根路径
今天有个需求,后端实现单点登录,会返给我一个拼接的地址,自动跳转到我的页面上,类似这样的地址:http://localhost:8080/grc/login?businessType=grcT31
自动跳转到我的网页地址:http://localhost:8080/grc/myvue
发送请求的时候,本地的根路径是http://localhost:8080/grc/,但是测试的根路径就要换成http://10……:8080/grc/…
如果每次设置测试和本地的根路径,就会很麻烦,所以考虑拿到最开始后端给我地址的域名和端口,来作为请求的根路径,写道baseURL中
PS:http叫做协议,localhost叫做域名,8080是端口,如果其中有一个不一样,那就会产生跨域问题。
//获取地址栏的所有地址(后端给我返回跳转之后的)
var currentPath=window.document.location.href
//获取端口之后的所有地址
var pathName=window.document.location.pathname
我们再拿到pathName地址的第一个位置:
var position=currentPaht.indexOf(pathName)
最后通过截取,拿到前面的协议+域名+端口号,作为我们的根路径
var localhostPath=currentPath.substring(0,position)
打印看一下:
console.log(currentPath,pathName,position,localhostPath)
http://localhost:8080/grc/myvue/#/ /grc/myvue/ 21 http://localhost:8080