微信原生小程序封装网络请求wx.request

发布于:2024-05-14 ⋅ 阅读:(152) ⋅ 点赞:(0)
  1. 安装
npm install mina-request
  1. 构建

安装完成后需要在微信开发中工具中进行 npm 构建,
点击 工具 > 构建 npm

  1. 新建 http.js 文件
import WxRequest from 'mina-request'
// 对 WxRequest 进行实例化
const instance = new WxRequest({
	baseUrl: '你的请求根路径',
	timeout: 15000
})

// 配置请求拦截器
instance.interceptors.request = (config) => {
	// 判断是否有访问令牌 token 
	// 如果有,需要在 header 携带 token 参数
	const token = getStorage('token')
	if(token){
		config.header['token'] = token
	}
	return config
}

// 配置响应拦截器
instance.interceptors.response = async (response) => {
	// 解构出需要的数据,简化数据
	const { isSuccess, data }  =  response
	// 是否响应成功
	if(!isSuccess) {
		// 响应数据失败处理
		wx.showToast({
			title: '网络异常请重试!',
			icon: "error",
		})
		return response
	}
	// 判断响应状态码
	switch (data.code) {
		// 200 成功
		case 200:
			return data
		// 208 没有 token,或者 token 失效,重新登录
		case 208:
		const res = await wx.modal({
			content: '身份失效,请重新登录!',
			showCancel: false
		})
		if(res){
			// 清除本地 token 或 本地存储数据
			clearStorage()
			// 跳转登录页面
			wx.navigateTo({
				url: '/pages/login/login',
			})
		}
		return Promise.reject(response)
		default:
		wx.toast({
			title: '出现异常,请重试!'
		})
		return Promise.reject(response)
	}
	
}

export default instance
  1. 使用
import instance from '../../utils/http'

page({
	async getInfo(){
		const res = await instance.get('您的请求地址')
		console.log(res)
	}
})


网站公告

今日签到

点亮在社区的每一天
去签到