赞
踩
整体思路:
//1.全局默认配置
//2.请求/响应拦截
//3.请求封装
//4.发送请求-处理数据 请求封装函数
代码详情:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="../axios.min.js"></script> <script src="../jquery-3.5.0.min.js"></script> <script> //1.全局默认配置 axios.defaults.baseURL = 'http://182.92.83.218:7788'; axios.defaults.headers.common['Authorization'] = sessionStorage.getItem('token'); axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; //2.拦截响应 axios.interceptors.response.use(function (response) { // 对响应数据做点什么 if(response.data.status==200){ return response.data }else{ alert(response.data.message) return Promise.reject(response.data) } }, function (error) { // 对响应错误做点什么 return Promise.reject(error); }); //3.请求封装 var request={ get:function(url,params){ return axios.get(url,params) }, post:function(url,data){ return axios.post(url,$.param(data)) }, postJSON:function(url,data){ return axios.post(url,data,{ 'Content-Type':'application/json' }) } } //4.发送请求-处理数据 var user={ password:123321, username:'admin1' } //登录,获取token request.postJSON('/user/login',user).then(response=>{ console.log('获取token',response) sessionStorage.setItem('token',response.data.token) }) //get 无参 查询所有栏目信息 request.get('/category/findAll').then(response=>{ console.log('get无参',response) }) //get 有参 分页查询用户信息 request.get('/baseUser/pageQuery',{ params:{ page:1, pageSize:10 } }).then(response=>{ console.log('get有参',response) }) //post 发送查询字符串 var category={ id:120, name:'邻居家的小妹妹', description:'有点beautiful' } request.post('/category/saveOrUpdate',category).then(response=>{ console.log('post发送查询字符串',response); }) </script> </head> <body> </body> </html>