一、axios介绍

Axios是一个基于Promise网络请求库,可以用于node.js 环境和浏览器环境使用。

在node.js框架中封装http模块,在浏览器中分装XMLHttpRequests对象。

支持PromoisAPI,支持拦截请求和响应,支持转换请求和响应数据,支持取消请求,支持自动转换JSON数据,支持客户端防御XSRF。

npm地址:axios - npm

二、axios 安装

1.nodejs 使用

npm install axios

2.浏览器使用

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

三、 axios 基本使用

1. 发送get请求

axios.get('http://xxxx/get?a=b&c=d')
    .then(function (response) {
        // 处理成功情况
        console.log(response.data);
        //response有几个重要的属性
        response.data
        response.status
        response.headers
    })
    .catch(function (error) {
        // 处理错误情况
        console.log(error);
    })
    .then(function () {
        // 总是会执行
        console.log('总是会执行')
    });

2.发送多个并发请求

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 API介绍

1.axios (config)  类似$.ajax()

// 发起一个post请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// 在 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 方法重载

  axios.request(config)
  axios.get(url[, config])
  axios.delete(url[, config])
  axios.head(url[, config])
  axios.options(url[, config])
  axios.post(url[, data[, config]])
  axios.put(url[, data[, config]])
  axios.patch(url[, data[, config]])

 在使用别名方法时, urlmethoddata 这些属性都不必在配置中指定

更多详细介绍参考:nodejs请求库axios(一) - 阿布_alone - 博客园

更多:

NodeJs 自定义日志记录工具分装_Nodejs 日志记录工具

Node js Http常用请求封装

使用webpack打包nodejs 后台端环境|NodeJs 打包后台代码

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。