基礎(chǔ)
下載:npm install(i) axios
引入:import axios from 'axios'
在miain.js文件中掛載到原型上Vue.prototype.axios=axios(這種方法比較low)
使用:
原型使用axios前加this:
axios({
url:'',
method:'get/post',
params:{}//get
data:{}//data
})
.then(res=>{})
.catch(err=>{})
//get
axios.get('地址',{
params:{}
})
.then(res=>{})
.catch(err=>{})
//post
axios.post('地址',data)
.then(res=>{})
.catch(err=>{})
攔截
let http=axios.create();
//請求攔截
http.interceptors.request.use(config=>{
return config
})
//響應(yīng)攔截
http.interceptors.response.use(response=>{
return response
})
模塊化
第一步:
下載:npm install(i) axios
第二步:
在scr文件夾下創(chuàng)建公通的common文件夾
common下創(chuàng)建一個axios基礎(chǔ)配置文件axiosConfig.js
import axios from 'axios' //引用
// import router from '../router' //路由引用誉察,若是在文件內(nèi)有涉及域帐,就要進(jìn)行引用
let http=axios.create();
//請求攔截
http.interceptors.request.use(config=>{
return config
})
//響應(yīng)攔截
http.interceptors.response.use(response=>{
return response
})
//拋出模塊
export default http
第三步:common下創(chuàng)建api文件痒谴,引入基礎(chǔ)配置
import http from './axiosConfig' //引入基礎(chǔ)配置
let getData = {} //拋出接口對象
//let baseUrl = "http://localhost:3000"
//改成代理服務(wù)器地址
let baseUrl = "/api" //這里基礎(chǔ)地址
//post的數(shù)據(jù)請求
import http from './axiosConfig'let getData = {}//let baseUrl = "http://localhost:3000"http://改成代理服務(wù)器地址let baseUrl = "/api"
//get的數(shù)據(jù)請求方式
getData.findManger = (data)=>{
return http.get(baseUrl + '/findManage',{ params:data })
}
//post的數(shù)據(jù)請求方式
getData.find = (data)=>{
return http.post(baseUrl + '/findManage',data )
}
export default getData
第四步:在頁面中進(jìn)行接口調(diào)用
import url from "../../util/api"; //進(jìn)行頁面引入
//調(diào)用接口
url.login(this.userInfo) //this.userInfo//傳遞的數(shù)據(jù)
.then(res=>{
//res請求回來的數(shù)據(jù)
}).catch(err=>{
//err錯誤信息
})