Axios的使用

时间:2019-10-22
本文章向大家介绍Axios的使用,主要包括Axios的使用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Axios的使用方法

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

实现步骤:

  • - 从浏览器中创建 [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
  • - 从 node.js 创建 [http](http://nodejs.org/api/http.html) 请求
  • - 支持 [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API
  • - 拦截请求和响应
  • - 转换请求数据和响应数据
  • - 取消请求
  • - 自动转换 JSON 数据
  • - 客户端支持防御 [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
// 在Vue全局变量设置了$axios =axios
//以后每个组件使用时:this.$axios
Vue.prototype.$axios = axios;
Vue.config.productionTip = false
// 配置公共的URL
axios.defaults.baseURL = 'http:/127.0.0.1:8800'

##### axios的get请求

```
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  
  $.ajax({
      url:'',
      type'get',
      success:function(data){
      },
      error:function(err){
    }
  })
```

#####  aixos的post请求

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

#### axios的默认配置

未来以后axios是一个局部作用域的那么我们可以通过

Vue.prototype.$axios = axios; 

此时我们就可以在任意组件中通过this.$axios获取到当前的axios实例


默认配置URL

axios.defaults.baseURL = 'http://127.0.0.1:8800'

axios实现一个登录的实例

<template>
  <div>
    <h1>用户登录</h1>

    <p>
      <input type="text" v-model="username"/>
    </p>
    <p>
      <input type="password" v-model="password"/>
    </p>
    <input type="button" value="登录" @click="doLogin"/>
  </div>
</template>

<script>
  export default {
    name: "login",
    data() {
      return {
        username:'',
        password:''
      }
    },
    methods:{
      doLogin(){
        var that = this;
        this.$axios.request({
          url:this.store.apiList.auth,
          data:{
            user:this.username,
            pwd:this.password
          },
          method:'POST',
          headers:{
            'Content-Type':'application/json'
          }
        }).then(function (arg) {
          if (arg.data.code === 1000){
            console.log(arg)
            that.$store.state.token = arg.data.token;
            that.$store.state.username = that.username;
            that.$store.commit('saveToken', {token:arg.data.token, username:that.username})
            var url = that.$route.query.backUrl;
            console.log(url);
            if(url){
              that.$router.push({path:url})
            }else {
              that.$router.push({path:'/index'})
            }
          }else {
            alert(arg.data.error)
          }
        }).catch(function (arg) {
          console.log('发送错误')
        })
      }
    }
  }
</script>

<style scoped>

</style>

原文地址:https://www.cnblogs.com/harryblog/p/11719318.html