小程序请求封装

9 篇文章 1 订阅
8 篇文章 0 订阅

小程序请求封装

小程序app.js文件
App({
  globalData: {
    apiHost: 'http://api:8888',
  }
  })
创建一个独立的 request.js 文件
request.js代码 注:(目前401表示未登录 200成功 500 接口请求错误)
注释就不详细说了 我有点懒 能看得懂就看吧! 上代码~
//获取app.js
const app = getApp();
//获取app.js里的globalData.apiHost的值  这里存的是接口地址
var serverUrl = app.globalData.apiHost;
//请求头逻辑判断
function CreateHeader(url, type) {
	let header = {}
	if (type == 'POST_PARAMS') {
		header = {
			'content-type': 'application/json',
			'token': wx.getStorageSync('token')
		}
	} else {
		header = {
			'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
			'token': wx.getStorageSync('token')
		}
	}
	return header;
}
//post请求,数据在body中
function postRequest(url, data) {
	let header = CreateHeader(url, 'POST');
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + url,
			data: data,
			header: header,
			method: 'POST',
			success: (res => {
				var data = res.data
				if (res.statusCode === 200) {
					wx.hideLoading()
					//200: 服务端业务处理正常结束
					if (res.data.code == 401) {
							wx.showToast({
								title: '请先登录',
								icon: 'none',
								duration: 1500,
								success() {
									var timer = setTimeout(function () {
										wx.navigateTo({
											url: `/pages/login/login`,
										})
										clearTimeout(timer)
									}, 1600);
								}
							})
			
					} else if (res.data.code == 500) {
						wx.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 1500,
						})
					}
					resolve(data)
				} else {
					wx.hideLoading()
					reject(data)
				}
			}),
			fail: (res => {
				wx.hideLoading()
				reject(res)
			})
		})
	})
}
//post请求,数据按照query方式传给后端
function postParamsRequest(url, data) {
	let header = CreateHeader(url, 'POST_PARAMS');
	let useurl = url;
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + useurl,
			data: data,
			header: header,
			method: 'POST',
			success: (res => {
				var data = res.data
				if (res.statusCode === 200) {
					wx.hideLoading()
					//200: 服务端业务处理正常结束
					if (res.data.code == 401) {
						wx.showToast({
							title: '请先登录',
							icon: 'none',
							duration: 1500,
							success() {
								var timer = setTimeout(function () {
									wx.navigateTo({
										url: `/pages/login/login`,
									})
									clearTimeout(timer)
								}, 1600);
							}
						})
					} else if (res.data.code == 500) {
						wx.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 1500,
						})
					}
					resolve(data)
				} else {
					wx.hideLoading()
					reject(data)
				}
			}),
			fail: (res => {
				wx.hideLoading()
				reject(res)
			})
		})
	})
}
//get 请求
function getRequest(url, data) {
	let header = CreateHeader(url, 'GET');
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + url,
			data: data,
			header: header,
			method: 'GET',
			success: (res => {
				var data = res.data
				if (res.statusCode === 200) {
					wx.hideLoading()
					//200: 服务端业务处理正常结束
					if (res.data.code == 401) {
						wx.showToast({
							title: '请先登录',
							icon: 'none',
							duration: 1500,
							success() {
								var timer = setTimeout(function () {
									wx.navigateTo({
										url: `/pages/login/login`,
									})
									clearTimeout(timer)
								}, 1600);
							}
						})
					} else if (res.data.code == 500) {
						wx.showToast({
							title: res.data.msg,
							icon: 'none',
							duration: 1500,
						})
					}
					resolve(data)
				} else {
					wx.hideLoading()
					reject(data)
				}
			}),
			fail: (res => {
				wx.hideLoading()
				reject(res)
			})
		})
	})
}
//put请求
function putRequest(url, data) {
	let header = CreateHeader(url, 'PUT');
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + url,
			data: data,
			header: {
				'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
				'token': wx.getStorageSync('token')
			},
			method: 'PUT',
			success: (res => {
				var data =res.data
				if (res.statusCode === 200) {
					//200: 服务端业务处理正常结束
					resolve(data)
				} else {
					reject(data)
				}
			}),
			fail: (res => {
				reject(res)
			})
		})
	})
}
//putJSON请求
function putJsonRequest(url, data) {
	let header = CreateHeader(url, 'PUT');
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + url,
			data: data,
			header: {
				'content-type': 'application/json',
				'token': wx.getStorageSync('token')
			},
			method: 'PUT',
			success: (res => {
				var data = res.data
				if (res.statusCode === 200) {
					//200: 服务端业务处理正常结束
					resolve(data)
				} else {
					reject(data)
				}
			}),
			fail: (res => {
				reject(res)
			})
		})
	})
}
//delete请求
function deleteRequest(url, data) {
	let header = CreateHeader(url, 'DELETE');
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + url,
			data: data,
			header: header,
			method: 'DELETE',
			success: (res => {
				var data = res.data
				if (res.statusCode === 200) {
					//200: 服务端业务处理正常结束
					resolve(data)
				} else {
					reject(data)
				}
			}),
			fail: (res => {
				reject(res)
			})
		})
	})
}
// 上传图片
const uploadFile = (url1, e) => {
	let option = e ? e : {};
	let url = url1 ? serverUrl + url1 : '';
	wx.showLoading({
		title: '上传中...',
	})
	return new Promise((resolve, reject) => {
		wx.uploadFile({
			url: url,
			filePath: option.filePath || '',
			name: option.name || 'file',
			header: option.header || {
				'content-type': 'multipart/form-data',
				'token': wx.getStorageSync('token')
			},
			formData: option.formData || {},
			timeout: option.timeout || 20000,
			success(res) {
				var data = JSON.parse(res.data)
				if (res.statusCode === 200) {
					wx.hideLoading()
					resolve(data)
					//200: 服务端业务处理正常结束
					if (data.code == 401) {			
						wx.showToast({
							title: '请先登录',
							icon: 'none',
							duration: 1500,
							success() {
								var timer = setTimeout(function () {
									wx.navigateTo({
										url: `/pages/login/login`,
									})
									clearTimeout(timer)
								}, 1600);
							}
						})
					} else if (data.code == 500) {
						reject(data)
						wx.showToast({
							title: data.msg,
							icon: 'none',
							duration: 1500,
						})
					}

				} else {
					wx.hideLoading()

				}
			},
			fail(res) {
				reject(res)
			},
			complete: function (res) {
				wx.hideLoading()
			}
		});
	})
}
//导出所有方法
module.exports.getRequest = getRequest;
module.exports.postRequest = postRequest;
module.exports.postParamsRequest = postParamsRequest;
module.exports.putRequest = putRequest;
module.exports.deleteRequest = deleteRequest;
module.exports.putJsonRequest = putJsonRequest;
module.exports.uploadFile = uploadFile;
存储接口地址文件requestaddress.js
//引入封装的请求文件
import {
	getRequest,
	postRequest,
	putRequest,
	postParamsRequest,
	putJsonRequest,
	uploadFile,
	deleteRequest
} from './request'

//api地址省略 已api代替
export const api= data => uploadFile(`/api/api/api/api`, data);

export const api= data => postRequest(`/api/api/api/api`, data);

export const api= data => getRequest(`/api/api/api/api`, data);

export const api= data => postParamsRequest(`/api/api/api/api`, data);

export const api= data => putJsonRequest(`/api/api/api/api`, data);

export const api= data => putRequest(`/api/api/api/api`, data);

export const api= data => deleteRequest(`/api/api/api/api`, data);

页面使用方式 home.js
const app = getApp();
import {
  api,
} from '../../utils/requestaddress.js'

//直接调用getdata就能获取接口数据了
getdata() {
    let that = this;
    api({
      id: 888,
    }).then(res => {
      console.log(res)
      if (res.code == 200) {
        let data= res.data;
        that.setData({
          data,
        })
      }else{
       	console.log(res.msg)
      }
    })
  },
感觉不错的 可以点个赞 支持前端小弟嘛~ ~ 制作不易 越努力越优秀!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Frontend-Arway

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值