微信原生小程序封装网络请求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)
	}
})
相关推荐
誰在花里胡哨17 小时前
微信小程序实现陀螺仪卡片景深效果
前端·微信小程序·动效
XXXFIRE18 小时前
微信小程序开发实战笔记:全流程梳理
前端·微信小程序
Thomas游戏开发19 小时前
Cocos Creator 面试技巧分享
面试·微信小程序·cocos creator
小小愿望21 小时前
微信小程序开发实战:图片转 Base64 全解析
前端·微信小程序
两个月菜鸟1 天前
vue+微信小程序五角星
vue.js·微信小程序·notepad++
Hashan1 天前
微信小程序:扁平化的无限级树
前端·微信小程序·uni-app
程序员陆通2 天前
零基础AI编程开发微信小程序赚流量主广告实战
微信小程序·小程序·ai编程
编程猪猪侠2 天前
解决uni-app微信小程序编译报错:unexpected character `1`
微信小程序·小程序·uni-app
Hashan3 天前
微信小程序:实现证件OCR识别
前端·vue.js·微信小程序
一念杂记3 天前
【实战系列3】免费可商用微信商城小程序开发——商品管理和展示
后端·微信小程序·开源