总结一些好用的请求封装.和uniapp里面自己封装的发送请求的插件
这个是最简洁的配置
import axios from 'axios' // 配置请求的跟路径 axios.defaults.baseURL = 'XXXXXXX' axios.interceptors.request.use(config => { config.headers.Authorization = window.sessionStorage.getItem('token') // 在最后必须 return config return config }) axios.interceptors.response.use(config => { return config }) Vue.prototype.$http = axios
使用:
this.$http.get('menus')
this.$http.post('login', {data})
这个是七一九的配置,写的很全
在apiset.js中
const serviceModule = {} const BasicDomain = 'XXXXXXXXXX' //图片本地调试 //图片获取 const getPictureUrl = BasicDomain + 'XXXXXXXXXXXXXXX' const secondaryDomain = '/admin' //公用部分
/*登录*/
serviceModule.Login = function() {
var p = {
url: '/system/login',
method: 'post'
}
return p
}
const ApiSetting = { ...serviceModule }
export default ApiSetting
在index.js中
import axios from 'axios'
import qs from 'qs'
import { Message } from 'element-ui'
import store from '../store/store'
//全局后台接口请求地址()
//const mainUrl = 'XXXXXXXXXX'
if (sessionStorage.getItem('token')) {
window.token = sessionStorage.getItem('token')
}
function getToken() {
return sessionStorage.getItem('token')
}
const httpServer = (opts, data, type = '') => {
let Public = {
//公共参数
}
let httpDefaultOpts = {
//http默认配置
method: opts.method,
baseURL: mainUrl,
url: opts.url,
timeout: 60000,
params: Object.assign(Public, data),
data: JSON.stringify(data)
}
if (type && type === 'downExcel') {
//下载excal数据流,无其他作用
httpDefaultOpts.responseType = 'blob'
}
try {
if (Object.prototype.toString.call(data) === '[object Array]') {
//判断是数组还是对象
httpDefaultOpts.data = data
} else {
httpDefaultOpts.data = Object.assign(Public, data)
}
} catch (e) {
httpDefaultOpts.data = Object.assign(Public, data)
}
httpDefaultOpts['headers'] = {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json;charset=UTF-8',
'Cache-Control': 'no-cache',
'If-Modified-Since': '0',
Authorization: store.state.token,
belong: 1,
userId: store.state.userId
}
if (type === 'upExcel') {
//兼容后台为formData接受数据用
httpDefaultOpts.headers['Content-Type'] = 'multipart/form-data; boundary=----WebKitFormBoundaryPXQ2z8zZHXQ5b4gL'
httpDefaultOpts.data = qs.stringify(data) //这里必须要用qs序列号过来的参数
}
if (opts.method == 'get') {
delete httpDefaultOpts.data
if (!!window.ActiveXObject || 'ActiveXObject' in window) {
//兼容某些IE get 请求会从缓存拿数据问题
if (httpDefaultOpts.url.indexOf('?') != '-1') {
httpDefaultOpts.url = httpDefaultOpts.url + '&timeStapIE=' + new Date().getTime()
} else {
httpDefaultOpts.url = httpDefaultOpts.url + '?timeStapIE=' + new Date().getTime()
}
}
} else {
delete httpDefaultOpts.params
}
let promise = new Promise(function(resolve, reject) {
axios(httpDefaultOpts)
.then(res => {
resolve(res)
})
.catch(response => {
reject(response)
})
})
return promise
}
axios.interceptors.request.use(
config => {
if ((config.data && !config.data.noloading) || (config.params && !config.params.noloading)) {
//Message.loading({
//content: 'Loading...',
//duration: 1
//});
}
return config
},
error => {
return Promise.reject(error)
}
)
axios.interceptors.response.use(
response => {
if (response.data.code && (response.data.code == 403 || response.data.code == 401)) {
//接口返回错误信息展示
Message.closeAll()
Message.error('登录已过期,请重新登录')
setTimeout(() => {
localStorage.clear()
sessionStorage.clear()
window.location.href = '#/login'
}, 1000)
return response.data
} else {
return response.data
}
},
error => {
if (error.data.code && error.data.code == 401) {
Message.error('登录身份过期,稍后请重新登录')
setTimeout(() => {
localStorage.clear()
sessionStorage.clear()
window.location.href = '#/login'
}, 1000)
} else if (error.data.code && error.data.code == 403) {
Message.error('登录身份过期,稍后请重新登录')
setTimeout(() => {
localStorage.clear()
sessionStorage.clear()
window.location.href = '#/login'
}, 1000)
} else if (error.data.code && error.data.code == 500) {
Message.error('服务异常,请稍后重试')
} else if (error.data.code && error.data.code == 404) {
//Message.error('找不到服务器');
} else {
//Message.error('请求服务器数据异常');
}
return Promise.reject(error)
}
)
export default { httpServer, mainUrl }
在main.js里面
import http from './api'
import ApiSetting from './api/apiset'
Vue.prototype.$http = http.httpServer
Vue.prototype.$mailUrl = http.mainUrl
Vue.prototype.GLOBALApi = ApiSetting
调用的时候
this.$http(this.GLOBALApi.marketTaskBudget(), {
taskId: taskId
}).then(res => {
}
})
写个插件.建一个文件夹utile.放request.js文件,在main.js里面引入request.js里面的代码
export default function (config) {
const {baseURL} = config
// 插件
return function(Vue){
Vue.prototype.http =async function (params){
// 解构请求的相关参数
const {url,methods,data} = params
//真正的请求
const res = await uni.request({
url:baseURL+url,
methods,
data
})
console.log(res[1].data)
}
}
}
在main.js里面的代码
import request from '@/utils/request'
const plugin = request({baseURL:'https://ugo.botue.com'})
vue.use(plugin )