博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
vue-cli的项目中关于axios的全局配置
阅读量:4499 次
发布时间:2019-06-08

本文共 2008 字,大约阅读时间需要 6 分钟。

1. 使用easy-mock.com来模拟数据接口

2. npm install axios 安装

3.新建目录

其中的http.js 里面是对axios请求接口的前期参数配置与后期数据的处理,直接上代码

import axios from 'axios'const instance = axios.create({    headers: {        'content-type': 'application/json;charset=UTF-8',        'token': 'one'     },    baseURL: 'https://easy-mock.com/mock/5c01e1f6f221b94c907213d6/',    timeout: 10000,    withCredentials: true})// 添加请求拦截器instance.interceptors.request.use(config => {    // 在发送请求之前做某事,比如说 设置token    config.headers['token'] = 'token';    return config;}, error => {    // 请求错误时做些事    return Promise.reject(error);});// 添加响应拦截器instance.interceptors.response.use(response => {    // 对响应数据做些事    if (response.status === 200) {        console.log(response)        if (response.data && response.data.data.code === 1) {            console.log('成功')            response.data.data.value = '我是返回成功' // 在请求成功后可以对返回的数据进行处理,再返回到前台        } else {            console.log('返回到登录...')        }    }    return response;}, error => {    return Promise.reject(error.response.data); // 返回接口返回的错误信息})export default instance;

index.js中就是对请求方法的简单封装,可以根据自己的需求来进行调整,代码如下

import axios from './http'var depot = {}depot.get = function ({ url, config = {}, cb }) {    axios.get(url, config).then((res) => {        if (res.status === 200) {            let result = res.data;            cb(result);        }    }).catch((error) => {        console.log('请求错误:' + error);    });};depot.post = function ({ url, data, cb }) {    axios.post(url, data).then(        (res) => {            if (res.status === 200) {                if (res.status === 200) {                    let result = res.data;                    cb(result);                }            }        }).catch((error) => {        console.log(error);    });};export default () => {    window.depot = depot;};

4. 在main.js中进行配置

5. 页面中的使用

  depot.get({      url: 'demo/demo',      data: {},      cb: (res)=> {        console.log(res)      }    })

这样一个简单的axios的全局封装就弄好了

 

转载于:https://www.cnblogs.com/qiuchuanji/p/10048805.html

你可能感兴趣的文章
深入分析 Java I/O 的工作机制(转)
查看>>
Python高级特性:迭代器和生成器 -转
查看>>
修炼编程的内功
查看>>
Ext JS - Ext.grid.feature.Grouping 分组表格
查看>>
ZConfig手册
查看>>
linux用户和用户组管理详解
查看>>
Jmeter之集合点
查看>>
JavaScript 基础,登录前端验证
查看>>
SQLite帮助类SQlitehelper 实现对SQLite数据的增删改查
查看>>
【转】字符、字符数组、char、string的区别分析
查看>>
HDU-3660 Alice and Bob's Trip 树形dp
查看>>
OpenLayers 搭建跨域代理(WFS)
查看>>
关于cros解决跨域的一个小例子(判断IP地址选择加不加跨域)
查看>>
图画hadoop -- 入门学习路线
查看>>
C#整理2——C#的输入输出及基本类型
查看>>
递归方法求解Fibonacci数列
查看>>
事件处理
查看>>
vue编辑回显问题
查看>>
我在博客园安家了
查看>>
SQL SERVER 数据库日期算法总结
查看>>