uniapp之luch-request使用大全:this.$http.post、get【this.$http.post使用form-data表单解决方案】

安装

cmd:

yarn add luch-request

main.js中:

import Request from 'luch-request' //yarn
Vue.prototype.$http = new Request({
	// 全局配置
	baseURL: BaseUrl,
	header: {
		/* 这个地方每次都调用 */
		"X-Access-Token": uni.getStorageSync('token')
	},
	method: 'GET',
	dataType: 'json',
	// #ifndef MP-ALIPAY
	responseType: 'text',
	// #endif
	// 注:如果局部custom与全局custom有同名属性,则后面的属性会覆盖前面的属性,相当于Object.assign(全局,局部)
	custom: {}, // 全局自定义参数默认值
	// #ifdef H5 || APP-PLUS || MP-ALIPAY || MP-WEIXIN
	timeout: 60000,
	// #endif
	// #ifdef APP-PLUS
	sslVerify: true,
	// #endif
	// #ifdef H5
	// 跨域请求时是否携带凭证(cookies)仅H5支持(HBuilderX 2.6.15+)
	withCredentials: false,
	// #endif
	// #ifdef APP-PLUS
	firstIpv4: ture, // DNS解析时优先使用ipv4 仅 App-Android 支持 (HBuilderX 2.8.0+)
	// #endif
	// 局部优先级高于全局,返回当前请求的task,options。请勿在此处修改options。非必填
	// getTask: (task, options) => {
	// 相当于设置了请求超时时间500ms
	//   setTimeout(() => {
	//     task.abort()
	//   }, 500)
	// },
	// 全局自定义验证器。参数为statusCode 且必存在,不用判断空情况。
	validateStatus: (statusCode) => { // statusCode 必存在。此处示例为全局默认配置
		return statusCode >= 200 && statusCode < 300
	}
});
// 示例:this.$http.get("url",param:{a:1,b:2}).then(()=>{}).catch(err=>{})
// 传json字符串this.$http.post('url',{a:"1",b:"2"}}).then(()=>{}).catch(err=>{})
// 传form-data表单this.$http.post('url',{a:"1",b:"2"},{header: {"content-type":"application/x-www-form-urlencoded"}}).then(()=>{}).catch(err=>{})
// 帮助:https://ext.dcloud.net.cn/plugin?id=392
// 详见https://www.quanzhan.co/archives/251 问题8

使用:
get:

this.$http.get("url",param:{a:1,b:2}).then(()=>{}).catch(err=>{})

post:

this.$http.post('url',{a:"1",b:"2"}}).then(()=>{}).catch(err=>{})

使用form-data表单进行post(使用form表单post)

this.$http.post('url',{a:"1",b:"2"},{header: {"content-type":"application/x-www-form-urlencoded"}}).then(()=>{}).catch(err=>{})

完整示例:

this.$http.post('/index/url',form)
				.then(res => {
					if (res.data.success) {
						console.log(res.data.result);
						//业务逻辑

					} else {
						uni.showToast({
							icon: 'none',
							title: '发起失败,请联系管理员!',
							duration: 2000
						})
						console.log(res);
					}
				}).catch(err => {
					uni.showToast({
						icon: 'none',
						title: '发起失败,请联系管理员!',
						duration: 2000
					})
					console.log(err);
				})

说明

官网:
https://ext.dcloud.net.cn/plugin?id=392
踩坑:
https://www.quanzhan.co/archives/251

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值