axios使用

import axios from 'axios'

/**
 * axios基本寫法
 */
axios({
        method: 'get', // post && get 
        url: 'xxx'
    })
    .then((response) => {
        console.log(response)
    })
    .catch((error) => {
        console.log(error)
    })

/**
 * API
 */
axios.get('url', {
        params: {
            abc: 'miaov',
            miaov: 'ketang'
        }
    })
    .then((response) => {
        console.log(response)
    })
    .catch((error) => {
        console.log(error)
    })

axios.post('url', {
        miaov: '課堂'
    })
    .then((response) => {
        console.log(response)
    })
    .catch((error) => {
        console.log(error)
    })

/**
 * 自定義請求配置
 */
//將query轉字符串的模塊
import queryString from 'queryString'

//創(chuàng)建取消請求令牌
let CancelToken = axios.CancelToken
let soure = CancelToken.source()

let HTTP = axios.create({
    baseURL: 'http://www.easy-mock.com/mock/59b39382e0dc663341a33b53/example/',
    timeout: 1000, //延時多少毫秒停止執(zhí)行
    responseType: 'json',
    params: {
        book: '123'
    },
    headers: {
        'custome-header': 'miaov',
        'content-type': 'application/x-www-form-urlencoded' //轉換data展現(xiàn)形式
    },
    transformRequest: [function (data) { //相當于中間件,用作發(fā)送數(shù)據(jù)轉換(處理),data參數(shù)為發(fā)送的ajax請求的data值
        // console.log(data)
        data.age = 20 //可以在函數(shù)里自行添加數(shù)據(jù)
        return queryString.stringify(data) //必須有返回值,要不是無法將數(shù)據(jù)傳送出去
    }],
    transformResponse: [function (data) { //用作返回數(shù)據(jù)的轉換
        // console.log(data)
        data: abc = 'miaov' //一樣可以自行添加返回數(shù)據(jù)
        return data //必須有返回值,否則請求的的返回值為undefined
    }],
    validateStatus(status) { //判斷狀態(tài)碼多少屬于成功,多少屬于失??;比較少使用
        return status < 400
    },
    CancelToken: source.token //需要使用再進行配置
})

// 使用方法:
HTTP.post('miaov', {
        miaov: 'ketang', //使用queryString.stringify() API只會把數(shù)據(jù)轉成 miaov:ketang username:leo的字符串形式
        username: 'leo' //如果想轉成miaov=ketang&username=leo形式,就需要在頭部添加content-type
    })
    .then((response) => {
        console.log(response)
    })
    .catch((error) => {
        if (axios.isCancel(error)) { //判斷人為取消請求還是服務器請求失敗
            console.log(error.message)
        } else {
            console.log(error)
        }

        // 取消請求調用
        source.cancel('用戶人為取消操作....')

    })

/**
 * 并發(fā)請求
 */
function http1() {
    return HTTP.get('miaov1')
}

function http2() {
    return HTTP.post('miaov2')
}

axios.all([http1(), http2()]) //axios.all(iterable) 并發(fā)請求
    .then(axios.spread((res1, res2) => { //axios.spread(callback) 接收并發(fā)請求并將返回的請求數(shù)據(jù)拆分
        console.log(res1)
        console.log(res2)
    }))
    .catch((error) => {
        console.log(error)
    })

/**
 * 全局攔截器
 */
//攔截請求
HTTP.interceptors.request.use(function (config) { //請求攔截,參數(shù)為自定義配置項信息
    //在發(fā)送請求前做某些事情
    return config //寫上返回值才能發(fā)送成功
}, function (error) {
    //請求錯誤時做些事
    return Promise.reject(error)
})

//攔截響應
HTTP.interceptors.response.use()

//取消攔截
HTTP.interceptors.request.eject(myInterceptpor)

/**
 * vue全局引用axios
 */
// npm install axios vue-axios --save
// Vue.use(VueAxios,Axios)
// this.$http[method]()

//如:
this.$http.get('url')
    .then((response) => {
        console.log(response)
    })
    .catch((error) => {
        console.log(error)
    })

//自定義配置使用:
Vue.prototyte.$http = HTTP


/**
 * PS:引用axios有三種方法:
 *  1.組件單獨引用
 *  2.全局引用
 *  3.vuex中單獨封裝,封裝在actions函數(shù)中,當單獨組件需要使用時,直接dispatch('ajaxHandle')進行調用
 *      (1).    http://www.jb51.net/article/110324.htm  詳細使用方式
 */
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容