Vue-CLI3.0项目搭建过程系列四:项目中axios应用

下面我们来说项目里的请求方法-axios

插播(来自网友):存储token建议state+localStorage
因为state是单页的,为了同一个浏览器打开第二个网页而不需要登录,所以要使用cookie或者localstorage存储,为什么不选用cookie1cookie存储量小;2cookie存储个数有限;3,其实是最重要的 请求时会带上cookie,增加网络负担,所以建议用state+localStorage,当然要处理好加密,过期等问题

api文件夹下新建index.js文件做axios的通用配置

import axios from 'axios'
import router from '../router/index'
import qs from 'qs'

// 创建axios实例
const service = axios.create({
    timeout: 10000 // 请求超时
})

// request拦截器
service.interceptors.request.use(config => {
    // 根据需要对数据进行转换处理:比如需要统一加上token值那么可以做如下处理
    if (!config.params) {
        config.params = {}
    }
    config.params.accessToken = localStorage.getItem('accessToken')
    if (config.method === 'post') {
        config.data = qs.stringify(config.data)
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    }

    return config
}, error => {
    Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(response => {
    // 根据需要对返回数据进行处理:根据前后端约定进行处理(比如用户未登录或权限过期时请求返回的处理)
    const res = response.data
    if (!res || res.code === -1) {
        // 权限过期跳转到登录页面
        window.location.href = '' // 登录页链接
    }
    return response
}, error => {
    if (!error || !error.response) {
        // 跳转500
        router.replace({
            path: '/500'
        })
    }
    // 检查状态
    switch (error.response.status) {
        case 402:
            // 清除token信息
            alert('登录过期,请重新登录')
            // 清除token信息
            localStorage.setItem('accessToken', '')
            // permissionUtil.logout()

            return error
        case 404:
            // 跳转404
            router.replace({
                path: '/404'
            })
            break
    }
    return Promise.reject(error)
})

export default service

api文件夹下新建constant文件里面定义项目里需要的所有接口

// 定义开发阶段的联调接口地址
const BASE_1 = ''

const env = process.env.NODE_ENV
let BASE
if (env === 'production') { // 生产环境 正式打包使用
    BASE = window.myConfig.baseUrl // 线上接口地址
} else if (env === 'development') { // 开发环境 本地测试使用
    BASE = BASE_1
}

// 定义需要的接口
const constant = {
    /*demo模块接口*/
    demo: BASE + 'https://api.apiopen.top/EmailSearch?number=1012002', // demo接口
}

export default constant

api文件夹下新建demo.js文件,这是一个示例文件-项目里我们可以分模块编写请求方法,每个模块一个js文件来放他的接口方法这样集中管理看起来比较有条理(我个人比较喜欢这种写法)

import axios from './index'
import constant from './constant'

/**
 * demo接口调用-get
 * @param param 关键字
 */
export function getDemo1(param) {
    return axios({
        url: constant.demo,
        method: 'get',
        params: param
    })
}

/**
 * demo接口调用-post
 * @param param 关键字
 */
export function getDemo2(param) {
    return axios.post(constant.demo, param)
}

view文件夹下新建demo文件夹-》新建index.vue文件,写一个使用请求方法的例子

<template>
    
</template>

<script>
    import { getDemo1 } from "../../api/demo"

    export default {
        name: "index",
        data() {
            return {
            }
        },
        methods: {
            // demo方法
            getDemo() {
                const that = this
                let param = {
                    data: 'test'
                }
                getDemo1(param).then((res) => {
                    if (res.data.code === 0) {
                        // 成功
                    } else {
                        // 失败
                        this.$message.error(res.data.msg)
                        return
                    }
                })
            }
        }
    }
</script>

<style scoped>

</style>

这时候我们可以正确请求到接口数据了

最终api文件结构如下:

接下来开始项目编写

猜你喜欢

转载自blog.csdn.net/liona_koukou/article/details/96427193