axios
基本使用
增删改查,get查,post增,put改,delete查
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<body> <buttonid="1">点我</button> <buttonid="2">点我2</button> <buttonid="3">点我3</button> <buttonid="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> |
默认配置
JS
1 2 |
axios.defaults.method='POST' axios.defaults.baseURL='http://localhost:3000' |
拦截器
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
//增加一个请求拦截器 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("请求拦截器失败") returnPromise.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 returnPromise.reject(error); }); axios({ method:'GET', url: 'http://localhost:3000/posts' }) |