axios
基本使用
增删改查,get查,post增,put改,delete查
代码语言:javascript复制<body>
<button id="1">点我</button>
<button id="2">点我2</button>
<button id="3">点我3</button>
<button id="5">点我5</button>
<script>
var btn = document.getElementById('1')
var btn2 = document.getElementById('2')
var btn3 = document.getElementById('3')
var btn5 = document.getElementById('5')
btn.onclick=function(){
axios({
method:'GET',
url: 'http://localhost:3000/posts',
}).then(response=>{
console.log(response)
});
}
btn2.onclick=function(){
axios({
method:'POST',
url: 'http://localhost:3000/posts',
data:{
title: "hello world",
author: "chenhao"
}
}).then(value=>{
console.log(value)
},reason=>{
console.log(reason)
});
}
btn3.onclick=function(){
axios({
method:'delete',
url: 'http://localhost:3000/posts/3',
}).then(value=>{
console.log(value)
},reason=>{
console.log(reason)
});
}
btn5.onclick=function(){
axios({
method:'PUT',
url: 'http://localhost:3000/posts/2',
data:{
title: "hello world",
author: "libai"
}
}).then(value=>{
console.log(value)
},reason=>{
console.log(reason)
});
}
</script>
</body>
默认配置
代码语言:javascript复制axios.defaults.method='POST'
axios.defaults.baseURL='http://localhost:3000'
拦截器
代码语言:javascript复制 //增加一个请求拦截器
axios.interceptors.request.use(function (config) {
// Do something before request is sent
console.log("请求拦截器成功")
return config;
}, function (error) {
// Do something with request error
console.log("请求拦截器失败")
return Promise.reject(error);
});
//增加一个响应拦截器
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
console.log("响应拦截器成功")
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
console.log("响应拦截器成功")
// Do something with response error
return Promise.reject(error);
});
axios({
method:'GET',
url: 'http://localhost:3000/posts'
})