vue網(wǎng)絡(luò)請求方案原生網(wǎng)絡(luò)請求和js網(wǎng)絡(luò)請求庫
一、?原生網(wǎng)絡(luò)請求
1. XMLHttpRequest(w3c標準)? ?
// 沒有promise時的產(chǎn)物
當(dāng)時的萬物皆回調(diào),太麻煩
2. Fetch? ?
// html5提供的對象,基于promise 因為promise的存在,為了簡化網(wǎng)絡(luò)請求。
Fetch是新的ajax解決方案 Fetch會返回Promise對象。fetch不是ajax的進一步封裝,而是原生js,沒有使用XMLHttpRequest對象。
參數(shù):
1、第一個參數(shù)是URL:
2、第二個設(shè)置請求的參數(shù),是可選參數(shù)
3、返回使用了Promise 來處理結(jié)果/回調(diào)
fetch(url, options).then(res=>res.json()/text()).then(ret=>console.log(ret))
兼容性問題:
ie低版本不兼容Fetch怎么辦? =》 用第三方的Fetch庫【fetch-polyfill】
使用fetch進行網(wǎng)絡(luò)請求 let url1 ?url2 ?兩個地址同時執(zhí)行完畢后才進行相關(guān)操作 Promise.all
let url1 不管它是否執(zhí)行成功我都要去處理 Promise.finally
?
?
二、 js網(wǎng)絡(luò)請求庫
axios
以promise類型返回 json 數(shù)據(jù)。
Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和node.js中。
能攔截請求和響應(yīng),自動轉(zhuǎn)換JSON數(shù)據(jù)。axios也是vue作者推薦使用的網(wǎng)絡(luò)請求庫。
// axios.get/post/put/delete axios.get(url,config) // config可以設(shè)置頭信息 axios.post(url,data,config) axios.put(url,data,config) axios.delete(url,data,config)
或通過實例請求
?
通過實例請求,添加設(shè)置信息(常用)!
不通過實例做統(tǒng)一設(shè)置(不常用),因為是給所有人都設(shè)置
// 統(tǒng)一給axios設(shè)置 axios.defaults.timeout = 10000 axios.defaults.baseURL = 'http://localhost:3000' axios.defaults.headers.a = 'admin'
post提交
// post提交 axios.post(url, { id: 1, name: 'aaaa' }).then(res => console.log(res.data))
?或者? ? axios直接用?# 標準寫法(也不常用)
// axios直接用 axios({ url, method:'get', data:{} }).then(res => console.log(res))
攔截器 ? 切面編程
(流水線)? ?(中間件)
1. 請求攔截器(能調(diào)用多次)
axios.interceptors.request.use(config => { // 統(tǒng)一設(shè)置請求域名地址 config.baseURL = 'http://localhost:3000' // 超時時間 config.timeout = 1000 // 設(shè)置頭信息 config.headers.token = 'mytoken login' return config; }, err => Promise.reject(err))
2. 響應(yīng)攔截器(處理、過濾)
axios.interceptors.response.use(response => { return response.data }, err => { // 可以在響應(yīng)攔截器中統(tǒng)一去處理,請求異常 alert('請求失敗了,請重新請求一次') return Promise.reject(err) });
以上就是網(wǎng)絡(luò)請求方案原生網(wǎng)絡(luò)請求和js網(wǎng)絡(luò)請求庫的詳細內(nèi)容,更多關(guān)于原生網(wǎng)絡(luò)請求和js網(wǎng)絡(luò)請求庫的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue-router配合ElementUI實現(xiàn)導(dǎo)航的實例
下面小編就為大家分享一篇vue-router配合ElementUI實現(xiàn)導(dǎo)航的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02