微信原生小程序封装网络请求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 小时前
小程序开发平台有哪些?小程序第三方开发平台评测对比
微信小程序
2501_9339072120 小时前
深圳本凡科技专业企业APP开发,助力手机应用创新优化
科技·微信小程序·小程序
java1234_小锋1 天前
分享一套优质的微信小程序校园志愿者系统(SpringBoot后端+Vue3管理端)
微信小程序·小程序·校园志愿者
“负拾捌”2 天前
python + uniapp 结合腾讯云实现实时语音识别功能(WebSocket)
python·websocket·微信小程序·uni-app·大模型·腾讯云·语音识别
换日线°3 天前
NFC标签打开微信小程序
前端·微信小程序
菜鸟una3 天前
【微信小程序+Taro 3+NutUI 3】input (nut-input) 、 textarea (nut-texteare)类型使用避坑
前端·vue.js·微信小程序·小程序·taro
计算机毕设指导63 天前
基于微信小程序的校园二手交易系统【源码文末联系】
java·spring boot·spring·微信小程序·小程序·tomcat·maven
Java.慈祥4 天前
速通-微信小程序 2Day
微信小程序·小程序·前端框架
2501_933907214 天前
宁波小程序公司是什么?主要提供宁波微信小程序制作与服务吗?
科技·微信小程序·小程序