zoukankan      html  css  js  c++  java
  • Vue2.0 搭配 axios

    1、安装axios

    $ npm install axios

    2、Demo

    (1)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);
      });

    (2)POST

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

    (3)多个并发请求

    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) {
        // 两个请求现在都执行完成
      }));

    3、常用方法:

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

    axios.request(config)
    axios.get(url[, config])
    axios.delete(url[, config])
    axios.head(url[, config])
    axios.post(url[, data[, config]])
    axios.put(url[, data[, config]])
    axios.patch(url[, data[, config]])
    NOTE
    在使用别名方法时, url、method、data 这些属性都不必在配置中指定。

    并发
    处理并发请求的助手函数

    axios.all(iterable)
    axios.spread(callback)

    4、一个登录的场景,用axios发送post请求去登录,能成功返回数据,但是用作权限验证的cookie就是没有保存,经查阅,axios 默认不发送cookie,跨域也是一个原因,需要全局设置

    axios.defaults.withCredentials = true 

    5、将axios发送的数据格式转换为form-data格式

    //npm install axios的时候默认会安装qs
    //qs相关的问题请搜索"nodejs qs"或者看这里https://www.npmjs.com/package/qs
    import qs from 'qs';
    
    // 将请求数据转换为form-data格式
    // 这里不用qs,用FormData也可以,不赘述
    var data = qs.stringify({
      currentPage: "0",
      pageSize: "10",
      type: "1",
    });
    
    axios.post('/url', data)
    .then(function (response) {
        //
    })
    .catch(function (error) {
    //
    });

    6、Vue-cli proxyTable 解决开发环境的跨域问题(在vue-cli的config文件index.js里有一个参数叫proxyTable)

    proxyTable: {
      '/list': {
        target: 'http://api.xxxxxxxx.com',
        changeOrigin: true,
        pathRewrite: {
          '^/list': '/list'
        }
      }
    }

    changeOrigin:设置true,本地虚拟一个服务端接收你的请求并代你发送该请求

  • 相关阅读:
    Linux 学习 -- 修改文件的权限(chmod)
    Spring MVC
    Spring AOP与IOC
    Java学习
    SSH学习
    Android之Service
    Android之操作相册
    Android之ListView优化
    Android之Bitmap 高效加载
    Android数据储存之SQLiteDatabase SQLiteOpenHelper类的简单使用
  • 原文地址:https://www.cnblogs.com/stonespawn/p/9668692.html
Copyright © 2011-2022 走看看