Axios 设置动态 baseURL

js动态获取项目部署时的路径,配置给Axios

js代码

//获取当前网址,如:http://localhost:8080/demo03/employee/page/1
let curWwwPath = window.document.location.href;
console.log("当前网址:"+curWwwPath)

//获取主机地址之后的目录,如 /employee/page/1
let pathName = window.document.location.pathname;
let pos = curWwwPath.indexOf(pathName)
let eee = pathName.substring(pathName.substr(1).indexOf("/")+1)
console.log("主机之后的地址:"+eee);

//获取主机地址,如:http://localhost:8080
let localHostPath = curWwwPath.substring(0,pos);
console.log("主机地址:"+localHostPath)

//获取带"/"的项目名称,如:/Tmall
let projectName = pathName.substring(0,pathName.substr(1).indexOf("/")+1)
console.log("带'斜杠'的项目名称:"+projectName)

//动态请求地址
axios.defaults.baseURL = localHostPath+projectName;
console.log("动态请求地址:"+axios.defaults.baseURL)

//删除单条员工信息
function deleteEmployee(empId,pageNum){
    axios({
        method: "post",
        url: "/employee/"+empId,
        params:{
            "_method":"delete",
            "pageNum":pageNum,
        }
    }).then(function (response) {
        //alert(response.data)
        location.reload();
    })
}

页面效果

发表评论