axios

官方文档地址:https://github.com/axios/axios

axios 是一个基于 Promise 的HTTP库,可以用在浏览器和 node.js 中

特性:

• 从浏览器发起 XMLHttpRequests 请求

• 从 node.js 发起 http 请求

• 支持 Promise API

• 拦截请求和响应

• 转换请求和响应数据

• 取消请求

• 自动转换为 JSON 数据

• 客户端支持防御 XSRF

补充Promise:

Promise 是 es6中新增的异步事件处理方式,基本用法如下:

复制代码
let myFirstPromise = new Promise((resolve, reject) => {
  // 当异步事件处理成功后自动调用 resolve(...)方法,如果失败的话则调用 reject(...)
  // 在这个例子中,我们使用setTimeout(...) 定时器来模拟异步事件
  setTimeout(function(){
    resolve("Success!"); // 此时,所有代码运行完毕
  }, 250);
});

myFirstPromise.then((successMessage) => {
    //successMessage 就是上面的resolve(...)方法中所传入的参数
  console.log("Yay! " + successMessage);
});


// Yay! Success!
复制代码

Promise对象是一个构造函数,它接收一个函数作为参数,该函数的两个参数分别是 resolve(字面意思:解决) 和 reject (字面意思:拒绝),它们是两个函数,由 js 引擎提供,不用自己部署。

resolve 函数的作用是,将 Promise 对象的状态从“未完成”变为“成功”,在异步操作成功时调用,并将异步操作的结果,作为参数传递出去。

reject 函数的作用是,将 Promise 对象的状态从“未完成”变为“失败”,在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去

上例中,myFirstPromise 是 Promise 对象创建的一个实例,Promise 实例生成后,可以用 then 方法分别指定 resolve 状态 和 reject 状态的回调函数,reject 函数是可选的,不一定要提供

getJSON('/posts.json').then(function(posts) {
  // ...
}).catch(function(error) {
  // 处理 getJSON 和 前一个回调函数运行时发生的错误
  console.log('发生错误!', error);
});

上面代码中,getJSON 方法返回一个 Promise 对象,如果该对象状态变为 resolved,则会调用 then 方法指定的回调函数;如果异步操作抛出异常,状态就会变为 rejected,同时调用 catch 方法指定的回调函数,处理这个错误。另外,then 方法指定的回调函数,如果在运行中抛出错误,也会被 catch 方法捕获

安装:

// 命令行输入
npm install axios

//引入 axios
import axios from 'axios'

官网提供的示例:

执行 GET 请求

复制代码
// 为给定 ID 的 user 发起请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 上面的请求也可以这么做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
复制代码

执行 POST 请求

复制代码
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
复制代码

执行多个并发请求

复制代码
function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求都已完成
  }));
复制代码

现在跟着官网的例子来操作下:

Demo 1:成功的发起一个 GET 请求

<button type="button" class="btn btn-primary" @click="get">get</button>
复制代码
import axios from 'axios';
    export default{
        methods: {
            get () {
                axios.get('../../../static/data/sidenav.json').then(response=>console.log(response))
                                       .catch(error=>console.log(error))
            }
        }
    }
复制代码

运行结果:

Demo 2:发起 GET 请求失败,依照上例,访问一个不存在的 hello.txt 文件

复制代码
import axios from 'axios';
    export default{
        methods: {
            get () {
                axios.get('./hello.txt').then(response=>console.log(response))
                                       .catch(error=>console.log('错误消息:'+error))
            }
        }
    }
复制代码

运行结果:

axios API

可以通过向 axios 传递相关配置来创建请求

复制代码
axios(config)

// 发送一个 POST 请求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// 从远程图片获取 GET 请求
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

axios(url[, config])

// 发送一个 GET 请求(默认方法)
axios('/user/12345');
复制代码

请求方法的别名:

为方便起见,所有被支持的请求方法都提供了别名

复制代码
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]])
复制代码

注意:在使用别名方法时,url、method、data 这些属性都不必在配置中指定

原文地址:https://www.cnblogs.com/annie211/p/8579135.html