You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
WeChat/src/utils/httpRequest.js

85 lines
2.7 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import Vue from 'vue'
import axios from 'axios'
import router from '@/router'
import qs from 'qs'
import merge from 'lodash/merge'
import { clearLoginInfo } from '@/utils'
const baseUrl = '/wx' // 设置请求的基础路径
// 创建axios实例
const http = axios.create({
timeout: 1000 * 30, // 设置请求超时为30秒
withCredentials: true, // 允许携带跨域请求的cookie
headers: {
'Content-Type': 'application/json; charset=utf-8' // 默认请求头为json格式
}
})
/**
* 请求拦截器
* 在每个请求发送之前加入token从cookie中获取
*/
http.interceptors.request.use(config => {
config.headers['token'] = Vue.cookie.get('token') // 在请求头中加入token
return config // 返回请求配置
}, error => {
return Promise.reject(error) // 请求出错时返回Promise拒绝
})
/**
* 响应拦截器
* 对响应数据进行拦截处理
* 如果返回的状态码为401未授权则清除登录信息并跳转到登录页
*/
http.interceptors.response.use(response => {
if (response.data && response.data.code === 401) { // 判断返回的code是否为401代表token失效
clearLoginInfo() // 清除登录信息
router.push({ name: 'login' }) // 跳转到登录页面
}
return response // 返回响应数据
}, error => {
return Promise.reject(error) // 响应出错时返回Promise拒绝
})
/**
* 请求地址处理函数
* @param {*} actionName 接口的名称拼接成完整的URL
* @returns {string} 拼接后的完整URL
*/
http.adornUrl = (actionName) => {
// 在开发环境下,如果开启了代理,则请求路径会带上代理前缀
return baseUrl + actionName // 返回完整的请求URL
}
/**
* get请求的参数处理
* @param {*} params 请求的参数对象
* @param {*} openDefultParams 是否开启默认参数
* @returns {object} 处理后的参数对象
*/
http.adornParams = (params = {}, openDefultParams = true) => {
const defaults = {
't': new Date().getTime() // 添加时间戳参数,防止缓存
}
return openDefultParams ? merge(defaults, params) : params // 合并默认参数和传入的参数
}
/**
* post请求的数据处理
* @param {*} data 请求的数据对象
* @param {*} openDefultdata 是否开启默认数据
* @param {*} contentType 数据格式类型('json'或'form'
* @returns {string} 处理后的数据
*/
http.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
const defaults = {
't': new Date().getTime() // 添加时间戳参数,防止缓存
}
data = openDefultdata ? merge(defaults, data) : data // 合并默认数据和传入的数据
// 根据不同的contentType处理数据格式
return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
}
export default http // 导出axios实例供其他模块使用