uniapp之请求拦截器和响应拦截器的使用
拦截器目录如下api.js (api配置)env.js (环境配置)interceptos (拦截器)index.js (导出配置)main.js (注入)页面使用页面展示目录如下api.js (api配置)export const api = {// 默认请求就是get请求user: {url: '/user',name: '用户信息',method: 'GET',},}env.js (环境配置
·
目录如下
api.js (api配置)
export const api = {
// 默认请求就是get请求
user: {
url: '/user',
name: '用户信息',
method: 'GET',
},
}
env.js (环境配置)
// prod 生产 dev 开发
const env = "test"
const prod = {
url: 'https://localhost:5000', // 线上环境'
appKey: 'WX_MINI_MEHZ'
}
const dev = {
url: 'https://localhost:5000', // 生产环境'
appKey: 'WX_MINI_MEHZ'
}
const test = {
url: 'https://localhost:5000', // 测试环境'
appKey: 'WX_MINI_MEHZ'
}
const config = {
dev,
prod,
test,
}
let baseURL = config[env].url;
let appKey = config[env].appKey
export {
baseURL,
appKey
}
interceptors (拦截器)
import { baseURL } from './env.js'
import { api } from './api.js'
import Store from '@/store/index.js'
// 请求拦截
const fetch = (url,opt) => {
console.log("opt",opt)
let urls = (api[opt.url]?.url || api[url]?.url);
let params = opt.params ? ('?'+Object.keys(opt.params).map(key=>key+'='+opt.params[key]).join('&')) : ''
opt.url = baseURL + urls + params
opt.method = opt.method || "GET";
var header = {}
if( Store.state.user.token) {
header = { Authorization: Store.state.user.token }
}
opt.header = {...opt.header,...header}
console.log("header",opt.header)
opt.data = opt.data || {};
return new Promise((resolve,reject) => {
let options = {}
Object.keys(opt).map(key=>{
if(key !== "params") {
return options[key] = opt[key]
}
})
uni.request(options)
.then(res => interceptorsRes(res,resolve,reject))
.catch(err=> interceptorsErr(err,reject))
})
}
// 响应拦截
const interceptorsRes = ([err,resp],resolve,reject) => {
const { code } = resp.data
if(code == 200) {
console.log("请求成功")
}
if(code == 401) {
console.log("未授权,跳转回登录页")
}
resolve(resp)
}
// 异常处理
const interceptorsErr = (err,reject) => {
console.log("网络异常",err)
reject(err)
}
export { fetch }
index.js (导出配置)
import { fetch } from './interceptors.js'
const obj = {
headerGET: {
"Content-type":'application/x-www-from-urlencoded'
},
headerPOST: {
"Content-type":'application/json'
},
}
// 通用接口请求
export const reqAll = (url,params,opt={}) => {
opt.data = params
opt.header = obj['headerPOST']
return fetch(url,opt)
}
// get请求
export const reqGet = (url,params,opt={}) => {
opt.header = obj['headerGET']
opt.method = "GET"
opt.data = params
return fetch(url,opt)
}
// post请求
export const reqPost = (url,params,opt={}) => {
opt.header = obj['headerPOST']
opt.method = "POST"
opt.data = params
return fetch(url,opt)
}
main.js (注入)
import { reqAll, reqGet, reqPost } from './fetch/index.js'
Vue.prototype.$reqAll = reqAll;
Vue.prototype.$reqGet = reqGet;
Vue.prototype.$reqPost = reqPost;
页面使用
getUserInfo1() {
this.$reqPost("user").then(res=>{
console.log("res",res)
})
},
页面展示
更多推荐
已为社区贡献2条内容
所有评论(0)