1.下载安装配置
1.文档结构
S-DB文件夹
------>db文件夹(用于连接数据库)
----->安装mongodb,
----->db-server.js
----->npm vue-axios axios
vue工程目录
----->vue.config.js
2.引入
在main.js中
import axios from ‘axios’
import VueAxios from “vue-axios”
Vue.config.productionTip = false
Vue.use(VueAxios,axios)
3.在vue.config.js中
module.exports={
devServer:{
port:'',
open:true,
proxy:'https://elm.cangdu.org',//配置开发服务器的代理
}
}
2.发送请求
1.get请求
this指当前vue;
可换成Vue.axios.get(); 在main中import Vue from ‘vue’
this.axios.get('/v1/get',{params:{usr:this.usr,pwd:this.pwd}})
.then(response=>{
console.log(response.data)
})
.catch(err=>{
console.log('请求错误:',err);
});
2.post请求
post默认传输的是json格式(这是axios的特性),后台默认只接收键值对。
所以用qs转换一下
除非后台app.use(bp.json());//支持json
import qs from '../../node_modules/querystring'
this.axios.post('/v1/post',qs.stringify({usr:this.usr,pwd:this.pwd}))
.then(response=>{
console.log(response.data)
})
.catch(err=>{
console.log('请求错误:',err);
});
3.请求拦截
在main.js中
axios.interceptors.request.use(
req=>{
// console.log('将要给后台-------',req);
//这里相当于中间站,所有不可以随便修改req,要继续返回给后台
return req;
}
)
axios.interceptors.response.use(
res=>{
// console.log('将要给前端--------',res);
//拦截后台返回给前端的消息,可以稍做处理
// 比如res.data,因为res还返回请求头之类的不需要的信息
return res;
}
)