百度中全是vue-cli中使用axios的方式,我需要用的是在html中引入axios.js

1、新建 httpRequest.js 文件,定义如下方法:

//axios封装post请求
function axiosPostRequst(url,data) {
    let result = axios({
        method: 'post',
        url: url,
        data: data,
        transformRequest:[function(data){
            let ret = '';
            for(let i in data){
                ret += encodeURIComponent(i)+'='+encodeURIComponent(data[i])+"&";
            }
            return ret;
        }],
        header:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    }).then(resp=> {
        return resp.data;
    }).catch(error=>{
        return "exception="+error;
    });
    return result;
}

//get请求
function axiosGetRequst(url) {
    var result = axios({
        method: 'get',
        url: url
    }).then(function (resp) {
        return resp.data;
    }).catch(function (error) {
        return "exception=" + error;
    });
    return result;
}

2、在html中引入vue.js、axios.js、httpRequest.js

<!--根据自己路径引入-->
<script src="js/vue.min.js"></script>
<script src="js/axios-0.19.js"></script>
<script src="js/httpRequest.js"></script>

3、在js文件中使用封装好的方法

var datas = {
    flag:'pass',
    comment:'通过'
};
axiosPostRequst('http://localhost:10001/account/approve',datas).then(result=>{
    consloe.log(result);
});

ok,大功告成,这样就不用每次请求时写一大串请求头、请求体了。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐