二次封装axios

235 阅读1分钟

axios post请求

// 发起一个post请求 
//--------方式一------------
axios({ 
    method: 'post', 
    url: '/user/12345', 
    data: { 
        firstName: 'Fred', 
        lastName: 'Flintstone' 
     }
 });
 //-------方式一-------------
 
 //-------方式二-------------
 axios.post('/user', { 
     firstName: 'Fred', 
     lastName: 'Flintstone' 
 }) 
 .then(function (response) { 
     console.log(response); 
 }) 
 .catch(function (error) { 
     console.log(error); 
 });
 //-------方式二-------------

axios get请求

// 在 node.js 用GET请求获取远程图片 
 //-------方式一-------------
axios({ 
    method: 'get', 
    url: 'http://bit.ly/2mTM3nY', 
    responseType: 'stream' 
}) 
.then(function (response) { 
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 
});
 //-------方式一-------------
 
  //-------方式二-------------
  axios.get('/user/12345/permissions')
  //-------方式二-------------

axios发起多个get请求

function getUserAccount() { 
    return axios.get('/user/12345'); 
} 
function getUserPermissions() { 
    return axios.get('/user/12345/permissions'); 
} 
Promise.all([getUserAccount(), getUserPermissions()]) 
.then(function (results) { 
    const acct = results[0]; 
    const perm = results[1]; 
});

axios配置项解释请访问axios官网

封装代码如下Script