微信原生小程序封装网络请求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)
	}
})
相关推荐
文心快码BaiduComate2 小时前
用Comate Zulu开发一款微信小程序
前端·后端·微信小程序
Emma歌小白2 天前
如何首次运行小程序后端
微信小程序
赣州云智科技的技术铺子2 天前
【一步步开发AI运动APP】十二、自定义扩展新运动项目1
微信小程序·小程序·云开发·智能小程序
海绵宝宝不喜欢侬3 天前
uniapp-微信小程序分享功能-onShareAppMessage
微信小程序·小程序·uni-app
亮子AI3 天前
【小程序】微信小程序隐私协议
微信小程序·小程序
毕设源码-钟学长3 天前
【开题答辩全过程】以 “旧书驿站”微信小程序的设计与开发为例,包含答辩的问题和答案
微信小程序·小程序
nodcloud4 天前
点可云进销存商城如何部署在微信小程序
微信小程序·小程序
项目題供诗5 天前
微信小程序开发教程(八)
微信小程序·小程序
拼图2095 天前
微信小程序——云函数【使用使用注意事项】
微信小程序·小程序
Q_Q5110082855 天前
springboot+python+uniapp基于微信小程序的旅游服务系统景点信息展示 路线推荐 在线预约 评论互动系统
spring boot·python·微信小程序·django·flask·uni-app