axios
基本使用
增删改查,get查,post增,put改,delete查
HTML
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
<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
12 |
axios.defaults.method='POST' axios.defaults.baseURL='http://localhost:3000' |
拦截器
JS
12345678910111213141516171819202122232425262728 |
//增加一个请求拦截器axios.interceptors.request.use(function (config) {// Do something before request is sentconsole.log("请求拦截器成功")return config; }, function (error) {// Do something with request errorconsole.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 dataconsole.log("响应拦截器成功")return response; }, function (error) {// Any status codes that falls outside the range of 2xx cause this function to triggerconsole.log("响应拦截器成功")// Do something with response errorreturnPromise.reject(error); });axios({method:'GET',url: 'http://localhost:3000/posts'}) |
