axios 请求

完整文档

官网文档

html

<input type="file" multiple  id="files">
<button onclick="postAxios()">上传文件s</button>
<p id="files_progress" style="width:0px; height: 10px; background-color: #0e90d2"></p>

 

定义配置项、拦截器

// 定义配置项
const instance = axios.create({
    // `method` 是创建请求时使用的方法,如果使用的不是 instance.get方法调用,会自动覆盖当前调用的方法,例如下面的 instance.post,后端接收到的请求方法就是 POST
    method: 'get', // default
    // 自动加在 `url` 前面
    baseURL: 'http://casphp.com/api/AjaxRequest/',
    // 请求超时
    timeout: 3000,
    // 设置header 信息
    headers: {
        'Authorization': 'tooken_value',
        'XX-Device-Type':'extra_head_data'
    },
    // `params` 是即将与请求一起发送的 URL 参数
    params: {
        id: 12345
    },
    // 作为请求主体被发送的数据
    data:{
        name:"axios",
        char:"中文"
    },
    // `withCredentials` 表示跨域请求时是否需要使用凭证
    withCredentials: true, // default
    // `onUploadProgress` 允许为上传处理进度事件
    onUploadProgress: function (progressEvent) {
        var file_data = document.getElementById('files').files;
        // 当有文件上传的时候显示进度条
        console.log(file_data.length)
        if(file_data.length>=1){
            console.log(progressEvent);
            // 如果是多个文件,总文件大小 与 已上传文件进度
            var progress=document.getElementById('file_progress');
            var pro_num=progressEvent.progress;
            progress.style.width=(pro_num.toFixed(2))*100+'px';
            progress.innerText=(pro_num.toFixed(2))*100+'%';
        }

    }
 });

// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    // 这里获取的header 与 js/jquery 数据请求成功后获取(跨域/同域)的完全一样
    console.log(response.headers);
    if(response.status==200){
        return response.data;
    }else{
        return Promise.reject(response.data);
    }
}, function (error) {
    // 对响应错误做点什么
    console.log(error.stack);
    var error_info='error: '+error.response.status+' '+error.response.statusText;
    return Promise.reject(error_info);
});

get 方法

// 发送 get 请求
function getAxios(){
    instance.get('jsAjaxGet').then(function (response) {
        // 取得 cookie
        console.log(document.cookie);
        console.log(response)
    }).catch(function (error) {
        console.log(error)
    });
}

// 调用示例
getAxios();

post 方法

// 发送 post 请求,并上传文件
function postAxios() {
    var fd = new FormData();
    // 上传单个、多个文件数据
    var file_data = document.getElementById('files').files;
    // 如果直接写 formData.append("server_files", files); 后端接收不到 server_files
    for (var i = 0; i < file_data.length; i++) {
        fd.append("files["+i+"]", file_data[i]);
    }
    // 发送数据
    fd.append('id',34);
    fd.append('name','abc');
    fd.append('char','中文字符');

    instance.post('jqueryAjax2',fd).then(function (response) {
        // 取得 cookie
        console.log(document.cookie);
        console.log(response)
    }).catch(function (error) {
        console.log(error)
    });
}

 axios 的跨域设置

// 单独设置
axios.defaults.withCredentials = true
// 或者在 axios 配置项中设置,表示跨域请求时需要使用凭证
withCredentials: true, 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章