您的当前位置:首页正文

vue中axios请求的封装的介绍(代码)

2020-11-27 来源:易榕旅网
本篇文章给大家带来的内容是关于vue中axios请求的封装的介绍(代码),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

1、发送请求模块目录

3798923958-5c95b3cb80568_articlex.png

2、/api/url中存放的是每个模块的URL

// 商品模块 product.js
const product = {
 sku: {
 list: '/product/product/speclist',
 options: '/product/product/options'
 }
}
export default product

// 公用请求模块 common.js
const common = {
 region: {
 provinces: '/region/region/list',
 cities: '/region/region/list'
 },
 upload: {
 image: '/product/product/upload'
 }
}
export default common

发送请求的时候只需要指定key(sku/list),如:this.$ajax('sku/list', param);假定axios设置的baseURL是http://prod.storm.com/api/,那么最终的请求地址:http://prod.storm.com/api/pro...

3.requireURLs.js

使用webpack提供的require.context将src/api/url下后缀为js的所有文件引入,并整理出一个对象。

let urls = {}
const req = require.context('./url', false, /\.js$/)

const requireAll = requireContext => requireContext.keys().map(i => {
 let url = requireContext(i)
 Object.assign(urls, url.default)
})
requireAll(req)
export default urls

整合common.js & product.js,最终得到的对象如下:

urls = {
 sku: {
 list: '/product/product/speclist',
 options: '/product/product/options'
 },
 region: {
 provinces: '/region/region/list',
 cities: '/region/region/list'
 },
 upload: {
 image: '/product/product/upload'
 }
}

4.ajax.js

import axios from 'axios'
import qs from 'qs'
import jsd from 'js-file-download'
import store from '@/store'
import urlObj from './requireURLs'
import { Message, MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'

const service = axios.create({
 baseURL: `${process.env.BASE_API}/api/`, // 不同环境(dev/prod/test)使用不同的baseURL
 timeout: 5000
})
service.interceptors.request.use(
 config => {
 // 上传文件时,config.data的数据类型是FormData,
 // qs.stringify(FormData)的结果是空字符串,导致报出上传文件为空的错误
 if (config.method === 'post' && config.data.constructor !== FormData) {
 config.data = qs.stringify(config.data)
 }
 if (store.getters.token) {
 config.headers.common['Auth-Token'] = getToken()
 // Auth-Token 登录过期后,重新登录不传token
 if (!config.headers.common['Auth-Token']) {
 delete config.headers.common['Auth-Token']
 }
 }
 return config
 },
 error => {
 Promise.reject(error)
 }
)
service.interceptors.response.use(
 response => {
 const res = response.data
 if (response.headers['content-type'].indexOf('application/vnd.ms-excel') !== -1) {
 let fileName = response.headers['content-disposition'].split('=')[1]
 jsd(res, fileName)
 return
 }
 if (res.code === 0) { // 和后台约定code:0代表请求成功
 return res
 } else {
 if (res.code === 18500) { // 和后台约定code:18500代表token未过期,但是被更新了
 handleLogin('您已被登出,请重新登录')
 } else if (res.code === 18501) { // 和后台约定code:18500代表token过期
 handleLogin('登录已失效,请重新登录')
 } else {
 // 统一处理接口的报错信息,如果需要具体到页面去处理,可以和后台另外约定一个code
 Message({
 message: res.msg,
 type: 'error',
 duration: 3 * 1000
 })
 }
 return Promise.reject(res)
 }
 },
 error => {
 console.log('err ' + error)
 let data = error.response.data
 Message({
 message: data.msg,
 type: 'error',
 duration: 3 * 1000
 })
 return Promise.reject(data)
 }
)

const handleLogin = title => {
 MessageBox.confirm(title, '提示', {
 confirmButtonText: '重新登录',
 showCancelButton: false,
 showClose: false,
 type: 'warning'
 }).then(() => {
 store.dispatch('FedLogout').then(() => {
 location.reload()
 })
 })
}

const ajax = (path, data = {}, options = {}) => {
 let url = path.indexOf('http') === -1 ? path.split('/').reduce((o, k) => {
 return o[k]
 }, urlObj) : path
 let method = options.method || 'post'
 let params = { url, method }

 if (options.method === 'get') {
 Object.assign(params, { params: data }, options)
 } else {
 Object.assign(params, { data }, options)
 }
 return service(params)
}

export default ajax

5.在src/plugins中创建一个ajaxPlugin.js,并在src/main.js中引用

// ajaxPlugin.js
import ajax from '@/api/ajax'

let ajaxPlugin = {}

ajaxPlugin.install = Vue => {
 Vue.prototype.$ajax = ajax
}

export default ajaxPlugin

// main.js
import ajaxPlugin from '@/plugins/ajaxPlugin'

Vue.use(ajaxPlugin)

6.发送请求:

this.$ajax('sku/list').then(res => {})

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript视频教程栏目!

显示全文