首先安装luch-request ,我是用插件中心直接导入,然后根目录下utils下放插件luch-request
根据文档在main.js里创建实例 在全局配置里可以设置默认参数和拦截器 静态参数就放在config里,比如type,event之列,动态的就使用拦截器传参,比如token。返回的参数也可以用拦截器来获取,比如response codes 判断登录状态、权限
//引入全局请求插件 import { http,api } from '@/config/common.js' // 全局挂载引入,配置相关在该index.js文件里修改 Vue.prototype.$http = http Vue.prototype.$api = api然后根目录下创建config目录,建立common.js。在这里引入插件,与全局配置,拦截器。 局部配置的优先级高于全局配置,这个根据需要使用
import Request from '@/utils/luch-request/index.js' export const apiBaseUrl = 'http://www.baidu.com' const api = new Request() const http = new Request() export { http, api } http.config.header = {website:'123dfdf465132'} api.config.header={aaaaaaa:'sdfsdfsdfsdfsd'} api.setConfig((config) => { /* 设置全局配置 */ config.header = { ...config.header, a: 1111111, // 演示 b: 2222 // 演示 } return config }) //请求前拦截,用来动态加参,例如token api.interceptors.request.use((config) => { // 可使用async await 做异步操作 config.baseURL = apiBaseUrl config.header = { ...config.header, token:uni.getStorageSync('token') // 'testaaa': '11' // 演示拦截器header加参 } // 演示custom 用处 // if (config.custom.auth) { // config.header.token = 'token' // } // if (config.custom.loading) { // uni.showLoading() // } /** /* 演示 if (!token) { // 如果token不存在,return Promise.reject(config) 会取消本次请求 return Promise.reject(config) } **/ return config }, config => { // 可使用async await 做异步操作 return Promise.reject(config) }) // 请求后 api.interceptors.response.use((response) => { console.log(response) return response }, (response) => { /* 对响应错误做点什么 (statusCode !== 200)*/ console.log(response) console.log(response.statusCode); //未登录时清空缓存跳转 if(response.statusCode ==401){ uni.clearStorageSync(); uni.switchTab({ url:"/pages/user/user" }) } return Promise.reject(response) })用的时候在页面里直接调用
this.$http.post('/api/demo/test1', {userName: 'name', password: '123456'} ).then(res => { }).catch(err => { })