axios request in vue

How to initiate a request in vue?

Use axios to initiate requests, but configuration is required in the early stage

First install axios

Can be installed using npm, yarn, etc.

  1. npm installation method
npm install axios -sava //在项目文件夹中打开cmd或者终端进行安装依赖
  1.  yarn installation method
yarn add axios

Introducing axios. I usually create a utils folder under src, and create a new request.js in it to place the encapsulated axios.

 2. Create an instance

// 创建实例
const instance = axios.create()

// 创建实例后修改默认值
axios.defaults.baseURL = process.env.NODE_ENV == 'development' ? 'http://127.0.0.1:8081' : 'https://api.example.com' // 默认请求地址,需根据环境判断请求的路径
axios.defaults.timeout = 10000 // 超时时间,单位毫秒
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded' // post请求头的设置

 3. Request interception

/**
 * 请求拦截器
 * 每次请求前,如果存在token则在请求头中携带token
 */
axios.interceptors.request.use(
    config => {
        LoadingBar.start()
        // 添加token
        const token = getToken()
        token && (config.headers.Authorization = "Bearer " + token)
        return config
    },
    error => Promise.error(error)
)

4. Response interception 

/**
 * 响应拦截器
 * 每次请求后,判断请求状态码是否正确,及数据做处理
 */
axios.interceptors.response.use(
    /**
     * 传输层:接口正常或异常,用http状态码
     * 业务层:业务正常或异常,用自定义状态码
     */
    // 请求成功
    res => {
        LoadingBar.stop()
        // HTTP 状态码
        if (res.status !== 200) {
            return Promise.reject(res)
        }

        // 业务状态码
        let code = res.data.code
        if (!code || code === 2000) {
            // 无code,则请求的是html页面;有code,则返回请求的数据
            return Promise.resolve(res.data)
        }

        errorHandle(code, res.data.msg)
        return Promise.reject(false)
    },
    // 请求失败
    error => {
        LoadingBar.stop()
        const { response } = error
        if (response) {
            // 请求已发出,但是不在2xx的范围 
            errorHandle(response.status, response.data.message)
            return Promise.reject(response)
        } else {
            tip('网络出现故障,请稍后再试')
        }
    }
)

5. Error handling 

/**
 * 请求失败后的错误统一处理
 * @param {Number} status 请求失败的状态码
 */
const errorHandle = (status, msg) => {
    // 状态码判断
    switch (status) {
        // 2002: 用户名/密码错误
        case 2002:
            tip('用户名或密码错误!')
            break
        // 4003: token过期,清除token并跳转登录页
        case 4003:
            toLogin("登录信息过期")
            break
        // 其他状态码
        ...
        default:
            tip('后台维护中,请稍后再试')
    }
}

/**
* 提示函数
*/
const tip = msg => {
    // 使用UI框架自带的错误弹框即可
    Vue.prototype.$msg.error(msg)
}

/**
 * 跳转登录页
 * 携带当前页面路由,以便在登录完成登录后返回当前页面
 */
const toLogin = async (msg) => {
    // 移除token、用户信息

    // 跳转登录页
    router.replace({
        path: '/login',
        query: {
            redirect: router.currentRoute.fullPath
        }
    })
}

Use axios

 1. Create an api interface

  Taking the user module as an example, create a new api folder in the src directory to store all interface requests of the project. Create a new user.js with the following code.

import axios from '@/utils/request'

/**
 * @description: 用户登录
 * @param {String} username 用户名
 * @param {String} password 密码(aes加密)
 */
export const userLogin = params => {
    return axios.post('/user/login', params)
}
// 其他user接口
...

Page usage

import { userLogin } from '@/api/user'

userLogin({
  username: this.username,
  password: this.password, // 记得加密QAQ
}).then(res => {
  this.$msg.success('登录成功')
})

Use alone without encapsulation

<script>

//页面引入
import axios from 'axios'

export default {
    data() {
        return {
            url:'https://xxxxxxxxxxxx.com/index.php?xxxxx'
        },
    },
    methods: {
        getVipAsklist(){
            axios.get(this.url).then(res => {
                console.log(res);
                if(res.data.result =='1'){
                    this.asklist = res.data.qa_lsit
                    this.asklist = this.asklist.map((item)=>{
                        return {
                            title:item.title,
                            content:item.content.replace(/\"/g, "&quot;")
                        }
                    })
                    console.log(typeof this.asklist[0].content)
                    this.agrement = res.data.xieyi
                    return
                }
                this.$message.error(res.msg)
            })
        },
    }
}
</script>

Perfect ending~

Guess you like

Origin blog.csdn.net/zhangxueyou2223/article/details/132466847