axios 封裝 在專案檔案較多時使用

2021-10-12 12:43:27 字數 2748 閱讀 6501

在src下建立api資料夾,在裡面建立http.js檔案(可隨意)
// src/api/http.js

import axios from

'axios'

axios.defaults.baseurl =

""// axios.defaults.baseurl =

""//全域性設定⽹絡超時

axios.defaults.timeout =

10000

;//設定請求頭資訊

axios.defaults.headers.post[

'content-type']=

;axios.defaults.headers.put[

'content-type']=

;// 請求***

axios.interceptors.request.use(

config =

>

return config;},

error =

>

)// 響應***

axios.interceptors.response.use(

// 請求成功

// res =

> res.status ==

=200 ? promise.resolve(res)

: promise.reject(res)

, res =

>}}

,// 請求失敗

error =

>

) window.location.href =

""}else

// 請求已發出,但是不在2xx的範圍

}else})

;// 封裝xiaos請求

// 封裝get請求

export function axios_get(url, params)

).then(res =

>

).catch(err =

>)}

)}// 封裝post請求

export function axios_post(url, data)

).catch(err =

>)}

)}// 封裝put請求

export function axios_put(url, data)

).catch(err =

>)}

)}// 封裝delete請求

export function axios_delete(url, data)

).then(res =

>

).catch(err =

>)}

)}export default axios;

//⼀定要匯出函式

//將我們http.js中封裝好的 get,post.put,delete 導過來

, p)

在自己的vue中匯入我們定義的方法介面

姓名<

/td>

年齡<

/td>

家鄉<

/td>

角色<

/td>

身高<

/td>

班級<

/td>

<

/tr>

for=

"item in data_list"

:key=

"item.id"

>

}<

/td>

}<

/td>

}<

/td>

for=

"i in item.roles"

:key=

"i.id"

>

}<

/p>

<

/td>

}<

/td>

}<

/td>

<

/tr>

<

/table>

"previous" @click=

"get_data(cur_page-1)"

>

<

/button>

v-for=

"num in num_page"

:key=

"num"

@click=

"get_data(num)"

>

}<

/button>

"next" @click=

"get_data(cur_page+1)"

>

<

/button>

<

/div>

<

/div>

<

/template>

// 導⼊api.js中定義的 axios函式

import

from

'../api/api'

export default },

methods:

).then(res=

>)}

,}, created(),

computed:,}

,};<

/script>

vue專案封裝axios

還是直奔主題吧,因為官方不推薦使用vue resource,而是推薦axios,所以這篇文章分享給大家我在自己的專案裡如何封裝axios,雖說將axios在main.js裡寫入vue的原型鏈作為vue的屬性 vue.prototype.http axios 直接用最原始的方法也能進行請求 這樣也不是...

react專案的axios封裝

分享乙個 react axios 的元件封裝 請求 帶token放請求頭 import axios from axios import qs from qs import from antd import cookies from js cookie export default function ...

vue專案中封裝axios

axios.defaults.timeout 100000 請求超時時間。請求位址 其實做到這裡也可以,不用去單獨封裝get post 等請求也可以直接呼叫的。然後就可以在vue頁面去呼叫了 mounted function then function response catch function...