微信原生小程序封装网络请求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)
	}
})
相关推荐
云起SAAS18 小时前
设备质保保修维修保质包换期查询H5抖音快手微信小程序看广告流量主开源
微信小程序·小程序
程序媛徐师姐1 天前
Java基于微信小程序的线上教育商城,附源码+文档说明
java·微信小程序·线上教育商城小程序·java线上教育商城小程序·线上教育商城微信小程序·线上教育小程序·线上教育微信小程序
peachSoda71 天前
小程序图片加载优化方案
前端·微信小程序·小程序
努力成为包租婆1 天前
【微信小程序-内嵌H5,微信开发工具上-页面没有更新】
微信小程序·小程序
计算机徐师兄1 天前
Java基于SSM的校园顺路代送微信小程序【附源码、文档说明】
java·微信小程序·ssm·校园顺路代送微信小程序·校园顺路代送·顺路代送微信小程序·java校园顺路代送微信小程序
百万蹄蹄向前冲1 天前
支付宝 VS 微信 小程序差异
前端·后端·微信小程序
人生导师yxc1 天前
微信小程序接入支付宝沙箱支付(http请求)
微信小程序·小程序
云起SAAS2 天前
日历黄历八字排盘紫微斗数奇门遁甲姓名分析号码吉凶命理抖音快手微信小程序看广告流量主开源
微信小程序·小程序·ai编程·看广告变现轻·日历黄历八字排盘紫微斗数
heyCHEEMS2 天前
用 分段渲染 解决小程序长列表卡顿问题
前端·微信小程序
qq_12498707532 天前
基于springboot的驾校预约管理小程序(源码+论文+部署+安装)
spring boot·微信小程序·小程序·毕业设计·计算机毕业设计·毕业设计源码