在Vue中使用axios
首先执行npm install axios -S本地安装axios
然后创建utils工具包 创建request.js即可使用post等请求
新建util包
import axios from 'axios'
const request = axios.create({
baseURL: 'http://localhost:9090',
timeout: 5000
})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config => {
config.headers['Content-Type'] = 'application/json;charset=utf-8';
// config.headers['token'] = user.token; // 设置请求头
return config
}, error => {
return Promise.reject(error)
});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response => {
let res = response.data;
// 如果是返回的文件
if (response.config.responseType === 'blob') {
return res
}
// 兼容服务端返回的字符串数据
if (typeof res === 'string') {
res = res ? JSON.parse(res) : res
}
return res;
},
error => {
console.log('err' + error) // for debug
return Promise.reject(error)
}
)
export default request
使用时
save() {
request.post("/user", this.form).then(res => {
if (res) {
this.$message.success("保存成功")
this.dialogFormVisible = false
this.load()
} else {
this.$message.error("保存失败")
}
})
},
例如
1.表单:
request.post(“http://localhost:服务器端地址/user/add”,this.form).then(res=>{
})
后端使用@RequestBody接收对象
2.地址后面跟随参数
request.post(“http://localhost:服务器端地址/user/add”,{
params:{
pageNum: this.pageNum,
pageSize: this.pageSize,
username: this.username,
}
}).then(res=>{
//执行体
})
后端需用@RequestParam接收
3.跟随变量
request.post(“http://localhost:服务器端地址/user/add/”+id).then(res=>{
})
后端则用@PathVariable接收id