zoukankan      html  css  js  c++  java
  • 15、vue项目封装axios并访问接口

    1.在src下新建util文件夹,在util下新建request.js文件:

    封装axios:

    import axios from 'axios'
    import QS from 'qs';
    // import store from '@/store/index.js';
    import { Message } from 'element-ui';  //element库的消息提示,可以不用
    
    // 环境的切换
    // if (process.env.NODE_ENV == 'development') { //开发
    //     axios.defaults.baseURL = '/api';}
    // else if (process.env.NODE_ENV == 'debug') { //测试
    //     axios.defaults.baseURL = 'https://www.ceshi.com';
    // }
    // else if (process.env.NODE_ENV == 'production') { //线上
    //     axios.defaults.baseURL = 'https://www.production.com';
    // }
    
    // 请求超时时间
    axios.defaults.timeout = 15000;
    
    // post请求头
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
    
    // 请求拦截器
    axios.interceptors.request.use(
        config => {
            // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
            const token = store.state.token;
            if (token) {  // 判断是否存在token,如果存在的话,则每个http header都加上token
                config.headers.Token = token;
            }
            return config;
        },
        error => {
            return Promise.error(error);
        });
    // 响应拦截器
    axios.interceptors.response.use(
        response => {
            if (response.status === 200) {
                return Promise.resolve(response);
            } else {
                return Promise.reject(response);
            }
        },
        // 服务器状态码不是200的情况
        error => {
            if (error.response.status) {
                console.log(error)
            }
            return Promise.reject(error.response);
        }
    );
    
    export function get(url, params) {
        return new Promise((resolve, reject) => {
            axios.get(url,
                {
                    params: params
                })
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    if (!err.response) {
                        Message({
                            showClose: true,
                            message: 'get请求错误',
                            type: 'error'
                        });
                    } else {
                        reject(err.data);
                        console.log(err.response, '异常2');
                    }
                })
        });
    }
    
    export function post(url, params) {
        return new Promise((resolve, reject) => {
            axios.post(url, params)
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    if (!err.response) {
                        Message({
                            showClose: true,
                            message: 'post请求错误',
                            type: 'error'
                        });
                    } else {
                        reject(err.data);
                        console.log(err.response, '异常2');
                    }
                })
        });
    }
    export function deletes(url, params) {
      return new Promise((resolve, reject) => {
           axios.delete(url, {
              data: params
              }).then(res => {
                   resolve(res.data)
                 }).catch(err => {
                     reject(err.data)
                })
              })
            }

    export function put(url, params) {
           return new Promise((resolve, reject) => {
            axios.put(url, params).then(res => {
             resolve(res.data)
              }).catch(err => {
          reject(err.data)
          })
         })
       }
    
    export default axios

    2:在util文件下再新建api.js文件:

    import { get, post } from './request'
    export function getTest(params) {
        return get(`/api/tbk/dg_optimus_material`, { id:params });
    }
    
    export function getNvZhuang(params) {
        return post(`/api/tbk/dg_material_optional `, params);
    }

    3:在html页面访问接口:

    import { getTest, getNvZhuang } from "@/util/api.js"; // 导入api接口
    
      mounted: function() {
        this.queryList();
      },
      methods: {
        //精选
        queryList() {
          let params = { pageNo: 1, pageSize: 20 };
          getTest(params)
            .then(res => {
              this.jingxuanlist =
                res.tbk_dg_optimus_material_response.result_list.map_data;
              console.log(this.jingxuanlist);
            })
            .catch(error => {
              console.log(error);
            });
        }
    }
    不存在一劳永逸的技术,唯有坚持不懈的努力.
  • 相关阅读:
    对象池使用时要注意几点
    Flash3D学习计划(一)——3D渲染的一般管线流程
    714. Best Time to Buy and Sell Stock with Transaction Fee
    712. Minimum ASCII Delete Sum for Two Strings
    647. Palindromic Substrings(马拉车算法)
    413. Arithmetic Slices
    877. Stone Game
    338. Counting Bits
    303. Range Sum Query
    198. House Robber
  • 原文地址:https://www.cnblogs.com/xlfdqf/p/11128089.html
Copyright © 2011-2022 走看看