前后端分离:WebAPI+Vue开发——远程数据请求axios

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fengkang511/article/details/82837701

前后端分离:WebAPI+Vue开发——远程数据请求axios

前后端分离:WebAPI+Vue开发——跨域设置

前后端分离:WebAPI+Vue开发——身份认证

本文没有Vue语法内容(Vue中文文档),只记录本人开发中遇到的难点

远程请求采用axios(axios中文文档,注意:IE11以下不支持axios)

ajax、axios、fetch之间的详细区别以及优缺点(https://blog.csdn.net/twodogya/article/details/80223508

Get请求:

axios.get('http://api.abc.com/api/user',{
    param:{Id:132}
}).then(function(response){
    console.log(response.data);
}).catch(function(error){
    console.log(error);
});

Post请求:

axios.post('http://api.abc.com/api/user',{
name:'frank',
sex:'1'
}).then(function (response){
    console.log(response.data)
}).catch(function(error){
    console.log(error);
});

原始请求:

axios({
url:'http://api.abc.com/api/user',
method:'post',
responseType:'json',
data:{
    name:'frank',
    sex:'1'
}
}).then(function(response){
    console.log(response.data);
}).catch(function(error){
    console.log(error);
})

response的结构如下:

{
    // 返回的数据
    data: {},
    // http状态码
    status: 200,
    //状态
    statusText: 'OK',
    // 返回结果的header头
    headers: {},
    //axios请求的配置内容
    config: {}
}

全局默认值设置

axios.defaults.baseURL = 'http://api.abc.com';

设置之后,axios的远程请求,不用再具体到域名,直接用 url:'/api/user'即可,实际项目中建议把POST、GET方法进行封装,统一调用,如有更换其他远程请求方式的需求(如ajax)会很方便,封装如下:

//axios的Post方法封装
function POST(url, data, method) {
    var tk = getCookie('token');
    if (tk) {
        axios({
            url: url,
            method: 'post',
            data: data,
            headers: { 'token': tk }
        }).then(function (response) {
            if (response.data.ret == -2)//没有访问权限
            {
                location.href = '/';
            }
            else if (response.data.ret == -1) {//程序错误
                console.log(response.data.msg);
            }
            else {
                method(response.data);
            }
        }).catch(function (error) {
            console.log(error);
        })
    }
}
//axios的Get方法封装
function GET(url, data, method) {
    var tk = getCookie('token');
    if (tk) {
        axios({
            url: url,
            method: 'get',
            data: data,
            headers: { 'token': tk }
        }).then(function (response) {
            if (response.data.ret == -2)//没有访问权限
            {
                location.href = '/';
            }
            else if (response.data.ret == -1) {//程序错误
                console.log(response.data.msg);
            }
            else {
                method(response.data);
            }
        }).catch(function (error) {
            console.log(error);
        })
    }
}

GET和POST方法也可以封装到一个里边,method是一个回调函数,处理得到的数据;getCookie是自己写的cookie获取方法,此处的token类似sessionid,放在了请求头中,作为一个用户身份识别标识使用,用户身份识别后续再写;response.data.ret和response.msg是API接口中自定义的请求状态和提示信息

猜你喜欢

转载自blog.csdn.net/fengkang511/article/details/82837701