页面引入及调用:
axios({
method: 'get',
url: 'http://localhost:3000/map/get'
}).then(response=>{
console.log('请求成功:' + response);
}).catch(error => {
console.log('请求失败:' + error);
});
get请求,传入参数 http://localhost:3333/get_table/?id=1&name=juejin
axios.get('http://localhost:3333/get_table/', {
params:{
name:'juejin',
id:1
}
params:this.user
})
.then(resp => {
console.log(resp);
}).catch(err => {
console.log(err);
})
post请求
axios({
method:'post',
url:'http://localhost:3000/map/add1',
data: {}
}).then(function(response){
console.log(response)
}).catch(function(error){
console.log(error);
})
简写:
axios.post('http://localhost:3000/map/add1',{})
.then(function(response){
console.log(response)
}).catch(function(error){
console.log(error);
})
axios全局引入
main.js
import axios from 'axios'
Vue.prototype.$http= axios;
axios.defaults.baseURL = 'http://127.0.0.1:3333/'
组件中请求的方式为
this.$http({
method: 'get',
url: 'map/get'
}).then(response=>{
console.log('请求成功:' + response);
}).catch(error => {
console.log('请求失败:' + error);
});
axios请求拦截封装
全局处理请求、响应拦截的处理,常见处理请求动画,错误码等
import axios from 'axios'
axios.defaults.baseURL = `http://127.0.0.1:3333`;
// 添加请求拦截器
// 在发送请求之前做些什么
axios.interceptors.request.use((config)=>{
return config;
})
// 添加响应拦截器
axios.interceptors.response.use((response)=>{
// 对响应数据做点什么
return response
}, err=>{
// 对响应错误做点什么
return Promise.reject(err);
})
export default axios
页面调用:
import axios from '@/api/index' //引入方式
axios({
method:'post',
url:'/map/add1',
data: {}
}).then(function(response){
console.log(response)
}).catch(function(error){
console.log(error);
})