微信原生小程序封装网络请求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)
	}
})
相关推荐
码云数智-大飞2 天前
自助建站系统哪个好?快速建站哪个平台好
微信小程序
大黄说说2 天前
微信小程序制作平台有哪些?SaaS小程序搭建平台推荐
微信小程序
Lucky小黄人3 天前
微信小程序查看备案号
微信小程序·小程序
码云数智-园园3 天前
小程序制作平台哪个好?微信小程序制作平台对比评测
微信小程序
毕设源码-郭学长3 天前
【开题答辩全过程】以 基于微信小程序的当当手办店铺为例,包含答辩的问题和答案
微信小程序·小程序
qq_24218863323 天前
微信小程序新年首页源码
微信小程序·小程序
qq_24218863326 天前
微信小程序AI象棋游戏开发指南
人工智能·微信小程序·小程序
予你@。7 天前
UniApp + Vue3 实现 Tab 点击滚动定位(微信小程序)
微信小程序·小程序·uni-app
码云数智-大飞7 天前
小程序商城哪个平台好?小程序商城制作平台深度对比
微信小程序
kyh10033811208 天前
微信小游戏《找茬找汉字闯关王》源码赠送
microsoft·微信·微信小程序·微信小游戏·找茬小游戏·微信找茬消除