记录一下封装在uniapp封装uview的网络请求

2,870 阅读1分钟

今天在使用uniapp需要用到网络请求了,因为之前用习惯axios了,结果发现axios在uniapp还有小程序用起来好麻烦,搞半天没整明白,去看uviewAPI发现有现成的网络请求给我们使用吗,效果跟axios差不多,感兴趣的小伙伴可以去看uview的官方文档,我贴一下我今天封装的网络请求

第一步新建一个request.js,将公共的配置信息配置完毕

module.exports = (vm) => {
	uni.$u.http.setConfig(config => {
		config.baseURL = 'http://sanxiancheng.vaiwan.com/api/v1/member/'
		config.timeout = 5000
		config.header = {
			'content-type': 'application/json' || 'application/x-www-form-urlencoded'
		}
		return config
	})
	uni.$u.http.interceptors.request.use(config => {
		config.data = config.data || {}
		return config
	}, config => {
		return Promise.reject(config)
	})
	uni.$u.http.interceptors.response.use(res => {
		if (res.data.code === 500) {
			uni.$u.toast('服务器错误')
		} else if (res.data.code === 401) {
			return uni.$u.toast('token过期')
		}

		return res.data
	})
}

第二步,将request文件导入到main.js中

image.png

第三步,就可以写接口了,写完自己引用即可

image.png