执行get请求
axios.get("url?id=13",{ /*params:{ name:123 //带参请求 }*/ }) .then(res=>{ //成功后执行 }) .cache(err=>{ //错误执行 }) .finally(function(){ //总是执行 })
执行post请求
axios.post("/user",{ firstName:"Fred", lastName:"ssass" }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); })
执行并发请求
function getUserAccount(){ return axios.get("/user/12"); } function getUserPermissions(){ return axios.get("/user/123/permission") } axios.all([getUserAccount(),getUserPermissions()]) .then(axios.spread(function(acct,perms){ //两个请求都成功 }))
通过传递相关配置来进行请求
//post请求 axios({ method:'post', url:'', data:{ firstName:'M', lastName:'t' } }) //get请求 axios({ method:'get', url:'', responseType:'stream' }) .then(function(response){ response.data.pipe(fs.createWriteStream('a.jpg')) })
创建实例
const instance = axios.create({ baseURL:'',//方便的设置路由的转发规则 headers:{"X-Custom-header":foobar}//通过请求头设置一些信息 })
拦截器interceptors
配置拦截器,对请求与响应进行处
// 添加请求拦截器 axios.interceptors.request.use(function (config) { //发送请求之前做一些事情 return config; }, function (error) { //捕捉错,对错误进行处理 return Promise.reject(error); }); // 添加响应拦截器 axios.interceptors.response.use(function (response) { //对响应结果做一些处理 /* if(data.code===200){ return data.data }else{ return response } */ return response; }, function (error) { return Promise.reject(error); });
params 的用法
let params = { keyWord: null, name: 'xxx', age: 22 } // 为 null 的属性都会被过滤掉,最终的请求 url 是 /person?name=xxx&age=22 instance.get('/person', { params })