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, 

 

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