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

  1. 安装
bash 复制代码
npm install mina-request
  1. 构建

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

点击 工具 > 构建 npm

  1. 新建 http.js 文件
javascript 复制代码
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. 使用
javascript 复制代码
import instance from '../../utils/http'

page({
	async getInfo(){
		const res = await instance.get('您的请求地址')
		console.log(res)
	}
})
相关推荐
小蒜学长9 小时前
基于springboot 校园餐厅预约点餐微信小程序的设计与实现(代码+数据库+LW)
数据库·spring boot·微信小程序
cookqq9 小时前
Cursor和Hbuilder用5分钟开发微信小程序
微信小程序·小程序·curosor
毕设源码-钟学长11 小时前
【开题答辩全过程】以 基于微信小程序的美发服务系统的设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
canglingyue12 小时前
微信小程序罗盘功能开发指南
微信小程序·小程序
三脚猫的喵15 小时前
微信小程序中实现AI对话、生成3D图像并使用xr-frame演示
前端·javascript·ai作画·微信小程序
海绵宝宝不喜欢侬16 小时前
UniApp微信小程序-实现蓝牙功能
微信小程序·uni-app
Python大数据分析19 小时前
uniapp微信小程序商品列表数据分页+本地缓存+下拉刷新+图片懒加载
缓存·微信小程序·uni-app
小白_ysf19 小时前
uniapp和vue3项目中引入echarts 、lime-echart(微信小程序、H5等)
微信小程序·uni-app·echarts·h5·lime-echart
imHere·19 小时前
UniApp 分包异步化配置及组件引用解决方案
微信小程序·uni-app·分包
canglingyue1 天前
微信小程序加速计开发指南
微信小程序·小程序