axios封装get/post

3,830 阅读1分钟

axios 是一个基于 Promise 用于浏览器和 node.js 的 http 客户端,有以下特征:

  • 从浏览器中创建 XMLHttpRequest
  • 从node.js 发出 http请求
  • 支持 promise api
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防止 CSRF/XSRF

执行get请求

//不带参数请求
axios.get('/user')
.then(function (res) {
    console.log(res);
})
.catch(function (error) {
    console.log(error);
});
// 向具有指定ID的用户发出请求
axios.get('/user?ID=12345')
.then(function (res) {
    console.log(res);
})
.catch(function (error) {
    console.log(error);
});
// 也可以通过 params 对象传递参数
axios.get('/user', {
    params: {
        ID: 12345
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

执行post请求

axios.post('/user', {
    userId:"123"
},{
    headers:{
        token:"abc"
    }
})
.then(function (res) {
    console.log(res);
})
.catch(function (error) {
    console.log(error);
});

通过配置方式发送请求

get:

// get 在params中定义
axios({
    url:"xxx.com",
    method:"get",
    params:{
        userId:"123"
    },
    headers:{
        token:"http-test"
    }
}).then(res=>{
    console.log(res.data);
})

post:

// post 在data中定义
axios({
    url:"xxx.com",
    method:"post",
    data:{
        userId:"123"
    },
    headers:{
        token:"http-test"
    }
}).then(res=>{
    console.log(res.data);
})

封装请求的好处是如果更改请求地址,只需要在封装的请求前缀中进行修改即可,有利于代码的维护。 基本思路为:

  • 创建一个util.js文件,分别编写get和post请求方法,
  • 手写的get,post方法,使用axios的请求方式
  • 向外抛出封装的get,post方法
  • 在需要请求的地方引入get,post方法使用即可
const host = "http://localhost:3000"    //自定义请求前缀

export function get(url,params) {      //传入axios请求需要的参数
  return new Promise((resolve,reject) => {
    axios({
      url: host + url,
      method: 'get',
      params: {
        article_id: params
      }
    })
    .then(res => {
       resolve(res.data)         //返回请求数据
    })
    .catch(err => {
      reject(err.data)          //返回错误
    })
  })
}

使用方法

function http() {
    get("url").then(res => {
         console.log(res.data)
    })
}