zoukankan      html  css  js  c++  java
  • Axios 的基本使用

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

      1. 从浏览器创建 XMLHttpRequests
      2. 从node.js 创建 http 请求
      3. 支持Promise API
      4. 拦截请求和响应
      5. 转换请求数据 和 响应数据
      6. 取消请求
      7. 自动转换 JSON 数据
      8. 客户端支持防御 XSRF

    <script type="text/javascript" src="node_modules/vue/dist/vue.js"></script>
    <script type="text/javascript" src="node_modules/axios/dist/axios.js"></script>

    使用前将 axios ,添加到 Vue的父类 对象中。 以保证 Vue对象下挂载的所有的组件, 都可以访问到 axios

    Vue.prototype.$axios = axios;
    // Vue的父类 prototype(原型) 挂载了一个 $axios, 这个$axios 执向的就是 axios
    // 然后因为所有的组件 都是 挂载到 Vue中的。就可以通过 this.$axios 拿到 axios 这个对象。

    为 axios 配置一些默认值:

    axios.defaults.baseURL = 'http://127.0.0.1:8888';
    // 配置公共的 url. 这样在进行url 的请求时。 就不用每次都去写,前面这些 协议 ip 端口,一类的信息。
    // 他会自动的进行, 拼接,然后访问

    axios 的 get 请求  

      // 为给定 ID 的user 创建请求      axios 实在promise 的基础上做的封装

    axios.get('/user?ID=12345')
        .then(function. (response){
            console.log(response)
        })
        .catch(function, (error){
            console.log(error)
        })

    对比 jquery 的代码,其实都是一个流程: jquery是基于es5的基础上 从http库中,做的封装

    $.ajax({
        url:"/user?ID=12345",
        type:"GET",
        success:function(response){
    //成功返回的数据 }, error:fucntion(error_data){
    //返回的错误 } })

     axios 的post请求 

    sendAjaxByPost(){
        // post 第二个参数是 要发送的数据, 这里可以提交任何的类型数据。 这要看后端要接受什么样的数据
        // 如果想要发送一个对象到 后端, 需要使用 URLSearchParams() 对数据,进行处理。
        var params = new URLSearchParams(); // 使用这个对象去处理
        params.append('name',"alex111");
    
    
        // 在Vue中使用es5的function 函数。 this的指向会指向到Window对象。
        // 解决办法就是在进入这个函数之前, 讲this用另外的变量保存起来。 然后在函数内部使用这个变量,所代表的this
    //var _this
    = this; // 把外层的this 赋值给 _this //this.$axios.post('/create', params).then(function (res){_this.datas = res.data}).catch((error)=>{}); // 另一种方式就是,在vue中 如果要使用函数的话,尽量使用 => 箭头函数。 这样能保证this的执向, // 一直都是指向当前的这个Vue 实例对象, 不会乱跑。 this.$axios.post('/create', params).then((res)=>{this.datas = res.data}).catch((error)=>{}) },
  • 相关阅读:
    读书笔记之理想设计的特征
    一些javascript 变量声明的 疑惑
    LINQ 使用方法
    Google MySQL tool releases
    读书笔记之设计的层次
    EF之数据库连接问题The specified named connection is either not found in the configuration, not intended to be used with the Ent
    转载 什么是闭包
    javascript面向对象起步
    Tips
    数据结构在游戏中的应用
  • 原文地址:https://www.cnblogs.com/chengege/p/10934128.html
Copyright © 2011-2022 走看看