一、Vue整合Axios
1.下载Axios:
npm install --save axios vue-axios
2.axios提供了设置根域名的方法。
在main.js全局入口文件中,设置:
import axios from “axios”;
axios.defaults.baseURL = ‘http://localhost:8080’
3.响应拦截
// 添加Axios响应拦截器
axios.interceptors.response.use(function (response) {
//console.log(‘响应拦截’,response)
return response.data;
}, function (error) {
console.log(error)
});
4.在需要使用的页面中引入
import axios from ‘axios’
二、1.当后端发送get请求,此时前端可以使用params传递参数
axios.get(“http://localhost:8080/后端请求路径”,{
params:{
属性:值,
属性:值
}
}).then(res=>{
if (res.code == 20000){ //此处的res就相当于R(因为在main.js中已经设置拦截) this.$message({ message:"登录成功", type:"success", duration:1000 }) }else { this.$message({ message:"登录失败", type:"error", duration:1000 }) }
})
前端要将json变成对象,加注解@RequestBody
2.当后端发送post请求,此时后台需要使用@RequestBody
axios.post(‘http://localhost:8080/后端请求路径’,{
username:‘张三’,
password:‘987654’
}).then(function(ret){
console.log(ret.data);
})axios.put(‘http://localhost:8080/后端请求路径’,{
username:‘张三丰’,
password:‘11111’
}).then(function(ret){
console.log(ret.data);
}).catch(function (err){
console.log(err)
})
方式1:
方式2: