vue如何发送网络请求,使用axios事半功倍!
目錄
一、axios使用
1.支持多種請(qǐng)求方式:
2.安裝
3.簡(jiǎn)單使用實(shí)例
4.發(fā)送并發(fā)請(qǐng)求
5.全局配置
二、axios的實(shí)例
1.為什么要?jiǎng)?chuàng)建 axios的實(shí)例呢?
2.使用
三、、axios模塊封裝
四、axios攔截器
一、axios使用
1.支持多種請(qǐng)求方式:
?? ?axios(config)
?? ?axios.request(config)
?? ?axios.get(url[, config])
?? ?axios.delete(url[, config])
?? ?axios.head(url[, config])
?? ?axios.post(url[, data[, config]])
? ? axios.put(url[, data[, config]])
?? ?axios.patch(url[, data[, config]])
2.安裝
npm install axios --save
3.簡(jiǎn)單使用實(shí)例
1.安裝 import axios from 'axios' 2.get請(qǐng)求 axios({// 默認(rèn)是geturl: 'http://localhost:8000/home/multidata',method: 'get' }).then((result) => {console.log(result) }) --- axios({//url: 'http://localhost:8000/home/data?type=sell&page=1',url: 'http://localhost:8000/home/data',params: {type: 'sell',page: 1},method: 'get' }).then((result) => {console.log(result) })4.發(fā)送并發(fā)請(qǐng)求
有時(shí)候,我們可能需求同時(shí)發(fā)送兩個(gè)請(qǐng)求
? ? 使用axios.all,可以放入多個(gè)請(qǐng)求的數(shù)組。
? ? axios.all([])?返回的結(jié)果是一個(gè)數(shù)組,使用axios.spread可將數(shù)組[res1, res2]展開(kāi)為res1,res2
axios.all([axios({url: 'http://localhost:8000/home/multidata' }), axios({url: 'http://localhost:8000/home/data',params: {type: 'sell',page: 1} })]).then((results) => {console.log(results) }) //axios.spread展開(kāi)(不太常用) axios.all([axios({url: 'http://localhost:8000/home/multidata' }), axios({url: 'http://localhost:8000/home/data',params: {type: 'sell',page: 1} })]).then(axios.spread((res1, res2) => {console.log(res1)console.log(res2) })) //數(shù)組的解構(gòu),對(duì)應(yīng)也有對(duì)象的解構(gòu){name, age} = obj axios.all([axios({url: 'http://localhost:8000/home/multidata' }), axios({url: 'http://localhost:8000/home/data',params: {type: 'sell',page: 1} })]).then(([res1, res2]) => {console.log(res1)console.log(res2) })5.全局配置
(1)在上面的示例中,我們的BaseURL是固定的
? ? 事實(shí)上,在開(kāi)發(fā)中可能很多參數(shù)都是固定的。
? ? 這個(gè)時(shí)候我們可以進(jìn)行一些抽取,也可以利用axios的全局配置
axios.defaults.baseURL = 'http://localhost:8000' axios.defaults.headers.post['Content-Type'] = 'application/x-www/form-urlencoded' axios.default.timeOut = 50000axios.all([axios({url: '/home/multidata' }), axios({url: '/home/data',params: {type: 'sell',page: 1} })]).then((results) => {console.log(results) })(2)常見(jiàn)配置項(xiàng)
請(qǐng)求地址
?? ?url:'/user',
請(qǐng)求類型
?? ?method:'get',
請(qǐng)根路徑
?? ?baseURL:'http://www.mt.com/apl,
請(qǐng)求前的數(shù)據(jù)處理
?? ?transformRequest: [function(data){}]
請(qǐng)求后的數(shù)據(jù)處理
?? ?transformResponse: [function(data){}],
自定義的請(qǐng)求頭
?? ?headers:{'x-requested-With':'XMLHttpRequest'},
URL查詢對(duì)象
?? ?params:{id:12},
查詢對(duì)象序列化函數(shù)
?? ?paramsSerializer: function(params){}
request body
?? ?data:{key:'a'}
超時(shí)設(shè)置s
?? ?timeout: 1000,
跨域是否帶 Token
?? ?withCredentials: false,
自定義請(qǐng)求處理
?? ?adapter: function(resolve, reject, config){},
身份驗(yàn)證信息
?? ?auth: {uname:", pwd: '12'},
響應(yīng)的數(shù)據(jù)格式j(luò)son/blob/ document/ arraybuffer/text/ stream
?? ?responseType:'json',
二、axios的實(shí)例
1.為什么要?jiǎng)?chuàng)建 axios的實(shí)例呢?
?? ?口當(dāng)我們從 axios模塊中導(dǎo)入對(duì)象時(shí),使用的實(shí)例是默認(rèn)的實(shí)例
?? ?口當(dāng)給該實(shí)例設(shè)置一些默認(rèn)配置時(shí),這些配置就被固定下來(lái)了.
?? ?口但是后續(xù)開(kāi)發(fā)中,某些配置可能會(huì)不太一樣.
?? ?口比如某些請(qǐng)求需要使用特定的 baseURL或者 timeouti或者 content-Type等
?? ?口這個(gè)時(shí)候我們就可以創(chuàng)建新的實(shí)例,并且傳入屬于該實(shí)例的配置信息.
2.使用
const instance1 = axios.create({// 全局實(shí)例配置baseURL: 'http://localhost:8000',timeOut: 5000 })instance1({url: '/home/multidata' }).then(res => {console.log(res) })三、、axios模塊封裝
import axios from 'axios' // 1.傳success、failure方法 export function request(config, success, failure) {//1.創(chuàng)建實(shí)例const instance = axios.create({baseURL: 'http://localhost:8000',timeOut: 5000})// 2.發(fā)送真正的網(wǎng)絡(luò)請(qǐng)求instance(config).then(res => {success(res)}).catch(err => {failure(err)}) } // 2.只傳config export function request2(config) {//1.創(chuàng)建實(shí)例const instance = axios.create({baseURL: 'http://localhost:8000',timeOut: 5000})// 2.發(fā)送真正的網(wǎng)絡(luò)請(qǐng)求instance(config.baseConfig).then(res => {config.success(res)}).catch(err => {config.failure(err)}) } // 3.使用Promise(axios本身是返回一個(gè)Promise,所以沒(méi)必要再次返回一個(gè)promise了) export function request3(config) {return new Promise((resolve, reject) => {//1.創(chuàng)建實(shí)例const instance = axios.create({baseURL: 'http://localhost:8000',timeOut: 5000})// 2.發(fā)送真正的網(wǎng)絡(luò)請(qǐng)求instance(config).then(res => {resolve(res)}).catch(err => {reject(err)})}) } // 4.簡(jiǎn)化 export function request4(config) {//1.創(chuàng)建實(shí)例const instance = axios.create({baseURL: 'http://localhost:8000',timeOut: 5000})// 2.發(fā)送真正的網(wǎng)絡(luò)請(qǐng)求return instance(config); } // 封裝網(wǎng)絡(luò)請(qǐng)求 import {request, request2, request3, request4} from './network/request' request({url: '/home/multidata' }, res => {console.log(res) }) request2({baseConfig: {url: '/home/multidata'},success: function(res) {console.log(res)} }) request3({url: '/home/multidata' }).then(res => {console.log(res) }).catch(err => {console.log(err) }) request4({url: '/home/multidata' }).then(res => {console.log(res) })四、axios攔截器
//1.創(chuàng)建實(shí)例const instance = axios.create({baseURL: 'http://localhost:8000',timeOut: 5000})// 1.1攔截器,必須return,否則拿不到東西instance.interceptors.request.use(config => {console.log('req攔截器success')// 比如config中的一些信息不符合服務(wù)器的要求// 比如每次發(fā)送網(wǎng)絡(luò)請(qǐng)求時(shí),都希望在界面顯示一個(gè)請(qǐng)求的圖標(biāo)// 某些網(wǎng)絡(luò)請(qǐng)求(比如登錄)必須攜帶一些特殊的東西console.log(config)return config}, err => {console.log('req攔截器fail')console.log(err)return err})instance.interceptors.response.use(response => {console.log('resp攔截器success中')return response.data}, err => {console.log('resp攔截器fail中')return err})// 2.發(fā)送真正的網(wǎng)絡(luò)請(qǐng)求instance(config).then(res => {success(res)}).catch(err => {failure(err)})總結(jié)
以上是生活随笔為你收集整理的vue如何发送网络请求,使用axios事半功倍!的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Vuex-全局状态集中式管理神器,做vu
- 下一篇: 第一个VueJs入门页面