zoukankan      html  css  js  c++  java
  • Vue复习六(vue-cli/axios)

    基础

    axios.get('/user?ID=12345')
      .then(function (response) {
        // 成功
        console.log(response);
      })
      .catch(function (error) {
        // 失败
        console.log(error);
      })
      .then(function () {
        // 上一次的结果
      });
    
    问号参数的请求
    axios.get('/user', {
        params: {
          ID: 12345
        }
      })
    
    post 请求
    axios.post('/user', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
    
    axios({
               method:'post',
               url:'/api2',
               data:params    // 参数
           })
    

    方法

    axios.request(config)
    axios.get(url[, config])
    axios.delete(url[, config])
    axios.head(url[, config])
    axios.options(url[, config])
    axios.post(url[, data[, config]])
    axios.put(url[, data[, config]])
    axios.patch(url[, data[, config]])
    

    请求配置

    {
      url: '/user',
      // 请求方法
      method: 'get', 
      // 更改请求数据
       transformRequest: function (data, headers) {
      //做任何要转换的数据, JSON形式
        return data;
      },    
       // 更改响应数据, 返回对象的形式
      transformResponse: (data,headers) => ({
                    name: 'xxx',
                    sex: 234
                }),    
       // 发送的自定义头信息    
      headers: {'X-Requested-With': 'XMLHttpRequest'},
       // 请求的参数
      params: {
        ID: 12345
      },    
     // 可选函数, 负责序列化 params
      paramsSerializer: function (params) {
        return Qs.stringify(params, {arrayFormat: 'brackets'})
      },   
     // 请求体发送的数据,用于post   
     // type : string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams     
      data: {
        firstName: 'Fred'
      },
      // 请求超时前的毫秒数。
    //如果请求的时间超过' timeout ',请求将被中止。
      timeout: 1000,     
      //只有HTTP基本认证可以通过该参数配置。
    //对于不记名的token,使用' Authorization '自定义头。
       auth: {
        username: 'janedoe',
        password: 's00pers3cret'
      },
      // 服务器将响应的数据类型
       //  'arraybuffer', 'document', 'json', 'text', 'stream'   
       // 浏览器 'blob'
      responseType: 'json',   
    }
    

    修改响应数据

    				// 数据,请求头
    transformRequest:(data,header) => '{"foo":"bar"}',
    

    拦截器

    你这拦截器可以写一个文件里,导入到main.js

    // http request 拦截器(请求)
    axios.interceptors.request.use(
        config => {
            if (store.state.token) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
                config.headers.Authorization = `token ${store.state.token}`;
            }
            return config;
        },
        err => {
            return Promise.reject(err);
        });
    
    // http response 拦截器(响应)
    axios.interceptors.response.use(
        response => {
            return response;
        },
        error => {
            if (error.response) {
                switch (error.response.status) {
                    case 401:
                        // 返回 401 清除token信息并跳转到登录页面
                        store.commit(types.LOGOUT);
                        router.replace({
                            path: 'login',
                            query: {redirect: router.currentRoute.fullPath}
                        })
                }
            }
            return Promise.reject(error.response.data)   // 返回接口返回的错误信息
        });
    // 设置默认失效的时间
    axios.defaults.timeout=2000;
    

    删除拦截器

    const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
    axios.interceptors.request.eject(myInterceptor);
    

    我的想法是写一个文件

    然后页面直接可以调用使用

    import axios from "axios";
    
    export class httpServer {
        constructor() {
        }
    
       static firstHttp(params) {
           return axios.post('/api2', {params: params}).then(res=>res.data)
        }
    
        static getVue(params) {
            return axios.get('/api3', params).then(res => res.data);
        }
    }
    

    决定自己的高度的是你的态度,而不是你的才能

    记得我们是终身初学者和学习者

    总有一天我也能成为大佬

  • 相关阅读:
    从GoogleClusterData统计每个用户的使用率、平均每次出价
    简单的大众点评爬虫
    导入GoogleClusterData到MySQL
    高斯分布(正态分布)
    解决Mysql无法导入存在null数据的问题
    使用Python操作MySQL
    [Vue warn]: Duplicate keys detected: '0'. This may cause an update error.
    css多行超出时,超出高度,显示省略号
    mock.js学习之路(二)easy-mock(Vue中使用)
    mock.js学习之路一(Vue中使用)
  • 原文地址:https://www.cnblogs.com/fangdongdemao/p/14398132.html
Copyright © 2011-2022 走看看