uview2.0封装网络请求(微信小程序最新登录方式)
一、网络请求和相应拦截器
// 此vm参数为页面的实例,可以通过它引用vuex中的变量 module.exports = (vm) => { // 初始化请求配置 uni.$u.http.setConfig((config) => { config.baseURL = http://127.0.0.1:8080/; return config }) // 请求拦截 uni.$u.http.interceptors.request.use((config) => { //根据custom参数中配置的是否需要token,添加对应的请求头 if(config?.custom?.auth) { config.header.token = uni.getStorageSync("token") } return config }, config => { // 可使用async await 做异步操作 return Promise.reject(config) }) uni.$u.http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/ if (response.data.code !== 200) { // 服务端返回的状态码不等于200,则reject() return Promise.reject(response) } // return Promise.reject 可使promise状态进入catch if (response.config.custom.verification) { // 演示自定义参数的作用 return response.data } return response }, (response) => { /* 对响应错误做点什么 (statusCode !== 200)*/ console.log(response) return Promise.reject(response) }) }
二、main.js文件引入拦截器 注意: 将此部分放在new Vue()和app.$mount()之间,才能App.vue中正常使用
// 引入请求封装,将app参数传递到配置中 require(./common/http.interceptor.js)(app)
三、创建API集中管理文件
const http = uni.$u.http // 登录接口(获取code) post请求 export const getLoginCode = (data) => http.post(wx/code/ + data) //登录接口(用户登录) post请求 export const realyLoginInfo = (params, config = {}) => http.post(wx/login, params,config)
四、登录页面引用API并使用
import {getLoginCode,realyLoginInfo} from @/common/http.api.js
五、登录页完整代码示例
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
保姆级微信双开教程