vue axios and package used in the project

A, axios installation

Installation: cd to the project directory at the command line:

npm install axios 

Axios not directly use Vue.use (axios) method, it is necessary to import a package to integrate specialized use axios:

  npm install --save axios vue-axios

main.js introduced:

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios); 

Note: Vue.use (VueAxios, axios) in order not change, otherwise an error: Can not read property 'protocol' of undefined
introduced at page js:

import axios from 'axios'

Second, the use

1. Packaging api

In a project I need to configure some axios request interceptors and interceptor response, and also needs to be unified management api, here a little sum up my approach. Directory structure is as follows:
-src
---- API
-------- index.js
---- Axios
-------- axios.js

Api index.js look for unified management interfaces, POST and get methods of example, where the object type is reqData:

import Ax from '../axios/axios'
import qs from 'qs'

/* 登陆 */
export function login(reqData) { return Ax.post('/api/login', qs.stringify(reqData)) }
/* 用户列表 */
export function getUserList(reqData) { return Ax.get('/api/users', { params: reqData }) }

2. Use

Login page

import { login } from '../service/api/index'

const params = { username: this.loginForm.name, password: this.loginForm.password }
login(params).then(res => {
	if (res.data.result_code === 'FAIL') {
        this.$alert('账号密码错误', {
            confirmButtonText: '确定'
    	})
		 return false
    } else {
		localStorage.setItem('token', 'Bearer ' + res.data.data.token)
        this.$router.push('/home')
    }
 })

Requesting user information:

import { getUserList } from '@/service/api/index'

const params = { 'page': this.page, 'limit': this.limit }
if (this.form.telephone !== '') {
	params.telephone = this.form.telephone
}
getUserList(params).then(res => {
	this.tableData = res.data.data.data
	this.total = res.data.data.total
	this.loading = false
})

3. axios Configuration

import axios from 'axios'
import router from '../../router'
axios.defaults.baseURL = '路径'
axios.defaults.withCredentials = false
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.headers.common['Authorization'] = localStorage.getItem('token')

/* 请求拦截 */
axios.interceptors.request.use(
    config => {
        if (localStorage.getItem('token')) {
            config.headers.Authorization = localStorage.getItem('token')
        }
        return config
    },
    err => {
        return Promise.reject(err)// 请求错误时,直接结束
    })

/* 响应拦截 */
axios.interceptors.response.use(
    response => {
        return response
    },
    err => {
        if (err.response) {
            switch (err.response.status) {
                    case 401:
                        localStorage.removeItem('token')
                        router.replace('/login')
                        break
            }
        }
        // return Promise.reject(err.response.data) // 请求错误时,直接结束
    })

export default axios

The need to change introduced into axios main.js after packaging:

import axios from './service/axios/axios'

If you want to directly axios, you can see axios documents

Third, when used post request, need to install qs

Use the command line tool, type in the project:

npm install qs

Upon completion of the installation components you need to use in:

import qs from	'qs’

qs.parse () are parsed into objects of the URL form
qs.stringify () is a sequence of objects into the form of a URL, to & splicing

https://github.com/Gesj-yean/vue-demo-collection documented use more outstanding plug-ins. Students have time to look at my top blog can thank you very much.

Published 27 original articles · won praise 4 · Views 2831

Guess you like

Origin blog.csdn.net/qq_39083496/article/details/98846155