axios 的简单使用

Vue

axios

  • Promise based HTTP client for the browser and node.js
    • 以Promise为基础的HTTP客户端,适用于:浏览器和node.js
    • 类似于ajax,用来发送请求,异步获取数据
  • 安装:npm i -S axios
导入 vue
1 导入 axios
2 Vue.prototype.$http = axios
  this.$http 方式来使用 axios
3 全局公共域名配置
  axios.defaults.baseURL = 'https://api.example.com'
4 HTTP请求的拦截器
  axios.interceptors.request
  axios.interceptors.response

5 注意:发送post请求的时候,参数需要额外的处理
import Vue from 'vue'
import axios from 'axios'
// 将 axios 添加到 Vue.prototype 中
Vue.prototype.$axios = axios

---
// 在组件中使用:
methods: {
  getData() {
    this.$axios.get('url')
      .then(res => {})
      .catch(err => {})
  }
}

---
// API使用方式:

axios.get(url[, config])
axios.post(url[, data[, config]])
axios(url[, config])
axios(config)

Get 请求

// url中带有query参数
axios.get('/user?id=89')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// url和参数分离,使用对象
axios.get('/user', {
  params: {
    id: 12345
  }
})

Post 请求

  • 不同环境中处理 POST请求
  • 默认情况下,axios 会将JS对象序列化为JSON对象。为了使用 application/x-www-form-urlencoded 格式发送请求,我们可以这样:
// 使用 qs 包,处理将对象序列化为字符串
var qs = require('qs')
axios.post('/foo', qs.stringify({ 'bar': 123 }))

// 或者:
axios.post('/foo', 'bar=123')
axios.post('/user', qs.stringify({
    firstName: 'Fred',
    lastName: 'Flintstone'
  }))
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

axios API

可以通过传递相关配置来进行请求axios。

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

全局配置

​```js // 设置请求公共路径: axios.defaults.baseURL = 'https://api.example.com'


### 拦截器
​```js
// 请求拦截器
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);
  });

官方链接:https://github.com/axios/axios

转载于:https://my.oschina.net/shuaihong/blog/1558205

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值