Vue中axios的使用备忘
1. 安装axios
npm i axios --save
2. main.js中引入axios
import axios from 'axios'
Vue.prototype.$axios = axios
3. 组件中使用axios
axios请求的方法简要列举如下:
get:获取数据,请求指定的信息,返回实体对象
post:向指定资源提交数据
put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容
patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新
delete:请求服务器删除指定的数据
3-1 get请求
this.$axios.get('/a.json',{
params: {
id:1
}
}).then(res=>{
console.log(res.data);
},err=>{
console.log(err);
})
this.$axios({
method: 'get',
url: '/a.json',
params: {
id:1
}
}).then(res=>{
console.log(res.data);
},err=>{
console.log(err);
})
3-2 post请求
this.$axios.post('/url',{
id:1
}).then(res=>{
console.log(res.data);
},err=>{
console.log(err);
})
$axios({
method: 'post',
url: '/url',
data: {
id:1
}
}).then(res=>{
console.log(res.data);
},err=>{
console.log(err);
})
let data = {
}
let formdata = new FormData();
for(let key in data){
formdata.append(key,data[key]);
}
this.$axios.post('/a.json',formdata).then(res=>{
console.log(res.data);
},err=>{
console.log(err);
})
3-3 put和patch请求
this.$axios.put('/url',{
id:1
}).then(res=>{
console.log(res.data);
})
this.$axios.patch('/url',{
id:1
}).then(res=>{
console.log(res.data);
})
3-4 delete请求
this.$axios.delete('/url',{
params: {
id:1
}
}).then(res=>{
console.log(res.data);
})
this.$axios.delete('/url',{
data: {
id:1
}
}).then(res=>{
console.log(res.data);
})
axios({
method: 'delete',
url: '/url',
params: { id:1 },
data: { id:1 }
}).then(res=>{
console.log(res.data);
})
4. axios并发请求_同时发送多个请求,统一处理返回值
this.$axios.all([
this.$axios.get('/a.json'),
this.$axios.get('/a.json')
]).then(
this.$axios.spread((goodsRes,classifyRes)=>{
console.log(goodsRes.data);
console.log(classifyRes.data);
})
)
5. axios实例
let instance = this.$axios.create({
baseURL: 'http://localhost:8080',
timeout: 2000
})
instance.get('/a.json').then(res=>{
console.log(res.data);
})
let instance = this.$axios.create();
instance.defaults.timeout = 3000;
this.$axios.get('/a.json',{
timeout: 3000
}).then()
6. 拦截器 – 在请求或响应被处理前执行拦截
6-1 请求拦截器
this.$axios.interceptors.request.use(config=>{
return config
},err=>{
return Promise.reject(err);
})
let instance = $axios.create();
instance.interceptors.request.use(config=>{
return config
})
6-2 响应拦截器
this.$axios.interceptors.response.use(res=>{
return res
},err=>{
return Promise.reject(err);
})
this.$axios.interceptors.request.eject(instance);
7 错误处理
this.$axios.get('/url').then(res={
}).catch(err=>{
console.log(err);
})
8. 取消请求–用于取消正在进行的http请求
let source = this.$axios.CancelToken.source();
this.$axios.get('/a.json',{
cancelToken: source
}).then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
9. 封装好的axios的工具类使用
9-1 工具类:http.js
import axios from 'axios';
import ElementUI from "element-ui";
axios.defaults.baseURL = ''
axios.defaults.timeout = config.http_timeout
axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response) {
if (error.response.status == 404) {
ElementUI.Message.error("Status:404,正在请求不存在的服务器记录!")
} else if (error.response.status == 500) {
ElementUI.Message.error(error.response.data.message || "Status:500,服务器发生错误!!")
} else {
ElementUI.Message.error(error.message || "Status:${error.response.status},未知错误!")
}
} else {
ElementUI.Message.error("请求服务器无响应!")
}
return Promise.reject(error.response);
}
);
var http = {
get: function(url, params={}, config={}) {
return new Promise((resolve, reject) => {
axios({
method: 'get',
url: url,
params: params,
...config
}).then((response) => {
resolve(response.data);
}).catch((error) => {
reject(error);
})
})
},
post: function(url, data={}, config={}) {
return new Promise((resolve, reject) => {
axios({
method: 'post',
url: url,
data: data,
...config
}).then((response) => {
resolve(response.data);
}).catch((error) => {
reject(error);
})
})
},
put: function(url, data={}, config={}) {
return new Promise((resolve, reject) => {
axios({
method: 'put',
url: url,
data: data,
...config
}).then((response) => {
resolve(response.data);
}).catch((error) => {
reject(error);
})
})
},
patch: function(url, data={}, config={}) {
return new Promise((resolve, reject) => {
axios({
method: 'patch',
url: url,
data: data,
...config
}).then((response) => {
resolve(response.data);
}).catch((error) => {
reject(error);
})
})
},
delete: function(url, data={}, config={}) {
return new Promise((resolve, reject) => {
axios({
method: 'delete',
url: url,
data: data,
...config
}).then((response) => {
resolve(response.data);
}).catch((error) => {
reject(error);
})
})
},
jsonp: function(url, name='jsonp'){
return new Promise((resolve) => {
var script = document.createElement('script')
var _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
script.id = _id
script.type = 'text/javascript'
script.src = url
window[name] =(response) => {
resolve(response)
document.getElementsByTagName('head')[0].removeChild(script)
try {
delete window[name];
}catch(e){
window[name] = undefined;
}
}
document.getElementsByTagName('head')[0].appendChild(script)
})
}
}
export default http;
9-2 工具类的使用实例:
================【说在前头_Zhaof--Http请求】
Vue中使用Axios,发起Http请求, -- 【http.js自己封装实现了,过程好艰难呀,好在最终完成了】
1. 在public/config.js中配置好Url地址,如:url_1; 【config.js在public/index中引用了,处处可用】
**************************************************************
let config = {
url_1: "http://127.0.0.1:8080/UserInfoApi",
url_2: "http://192.168.217.132:9090/Api",
springbootapi_url_zhaof: "http://127.0.0.1:9090/api",
http_timeout: 60000
}
**************************************************************
2. 在src/api/中的js文件新增方法,如下实例:userInfo, 这样Vue页面中处处可用,参考src/api/zhaof.js
**************************************************************
userInfo: {
url: config.url_1 +'/userInfo',
name: '测试使用自定义的htt2发起http请求',
get: async function(){
return await http.get(this.url)
}
},
**************************************************************
3. Vue中调用上方的userInfo请求:
***************************************************************
methods: {
async getInfo() {
console.log("开始执行userInfo_zhangshan03")
var res = await this.$api.zhaof.userInfo.get()
console.log(res)
if(res.code == "200"){
this.$message.success("接口请求成功!")
this.userId = res.data.userid
this.userName = res.data.username
this.email = res.data.email
this.passWord = res.data.password
}else{
}
console.log("执行userInfo结束_zhangshan03")
},
***************************************************************