axios

axios简介:

axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

  • 从浏览器中创建 XMLHttpRequest
  • 从 node.js 发出 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防止 CSRF/XSRF
    示例代码见:
    https://gist.github.com/huahua029/489e301ebb6c872ce6bbac8b9a743f69
var app = new Vue({
  el: '#app',
  data: {
    date: new Date(),
    posts: []
  },
  mounted: function(){
      let self = this
      axios.get('https://cnodejs.org/api/v1/topics?page=1&limit=10')
       .then(function(res){
           self.posts = res.data.data
        })
       .catch(res=>{
        console.log(res)
      })
  }
})

axios的get请求:

1.安装

npm install axios

2.加载

import axios from 'axios'

3.全局挂载

Vue.prototype.$http = axios;

4.发出请求

// 为给定 ID 的 user 创建请求
使用传统的function
getData(){
var self = this;
this.$http.get('https://cnodejs.org/api/v1/topics')
.then(function (res) {
//此处的this指向的不是当前vue实例
self.items = res.data.data
console.log(res.data.data)
})
.catch(function (err) {
console.log(err)
})
}
// 可选地,上面的请求可以这样做
两种传递参数的形式,注意这里的params
axios.get('/user', {
params: {
ID: 12345
}
})
axios.get('/user', {
ID: 12345
})
---------------------------------
axios.get('https://cnodejs.org/api/v1/topics?page=1&limit=15')

使用CNODE社区官方的API为例展开学习
获取主题列表API:https://cnodejs.org/api/v1/topics
参数:page页码
limit 每页显示的数量

axios的post请求:

// 为给定 ID 的 user 创建请求
使用传统的function
getData(){
var self = this;
this.$http.post(url,{
page:1,
limit:10
})
.then(function (res) {
//此处的this指向的不是当前vue实例
self.items = res.data.data
console.log(res.data.data)
})
.catch(function (err) {
console.log(err)
})
}

POST传递数据有两种格式:

  • form­data ?page=1&limit=48
  • x­www­form­urlencoded { page: 1,limit: 10 }

axios拦截器

在请求或响应被 then 或 catch 处理前拦截它们

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

axios在博客项目的应用:封装API

我们需要将api封装下,传入路径、方法、数据,我们可以得到结果

axios.defaults.baseURL = 'https://blog-server.hunger-valley.com'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.withCredentials = true

function request(url ,type='GET',data={}){
  return new Promise((resolve,reject)=>{
    let options = {
      url: url,
      method: type
    }
    if(type.toLowerCase === 'get'){
        options.params =  data
    }else{
      options.data = data
    }
    
    axios(options).then(res=>{
      if(res.data.status === 'ok'){
        resolve(res)
      }else{
        reject(res.data.msg)
      }
    })
  })
}

前三句话是全局的axios默认值

axios发送请求:

具体见文档“请求配置”,只有url是必须的。
// 发送 POST 请求

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

// 发送 GET 请求

axios.get('/user', {
    params: {
      ID: 12345
    }
  })

等价于
axios.get('/user?ID=12345')

我们在上例中,先对请求配置做了设置,然后再去发送请求。

在axios中,post请求接收的参数必须是form­data
qs插件—­qs.stringify

你可能感兴趣的:(axios)