request.uvue 1.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
<template>
	<view>
		<page-head :title="title"></page-head>
		<view class="uni-padding-wrap uni-common-mt">
			<view class="uni-hello-text">
				请点击按钮向服务器发起请求
			</view>
			<view class="uni-textarea uni-common-mt">
				<textarea :value="res"></textarea>
			</view>
			<view class="uni-btn-v uni-common-mt">
				<button type="primary" @click="sendRequest" :loading="loading">发起请求(Callback)</button>
			</view>
		</view>
	</view>
</template>
<script>
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
18
	import RequestTask from 'uts.sdk.modules.DCloudUniNetwork.RequestTask';
19 20 21 22 23 24
	const duration = 2000
	export default {
		data() {
			return {
				title: 'request',
				loading: false,
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
25 26 27
				res: '',
				task: null as RequestTask | null,
				pageVisible: false
28 29
			}
		},
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
30 31 32 33 34 35 36 37
		onLoad() {
			this.pageVisible = true;
		},
		onUnload() {
			this.pageVisible = false;
			uni.hideLoading();
			this.task?.abort();
		},
38 39
		methods: {
			sendRequest() {
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
				this.loading = true;
				this.task = uni.request({
					url: "https://unidemo.dcloud.net.cn/ajax/echo/text?name=uni-app",
					dataType: "json",
					responseType: "json",
					method: "POST",
					data: {
						platform: "ios",
					},
					header: {
						"Content-Type": "application/json",
					},
					timeout: 6000,
					sslVerify: false,
					withCredentials: false,
					firstIpv4: false,
					success(res) {
						if (this.pageVisible) {
							console.log('request success', res)
							uni.showToast({
								title: '请求成功',
								icon: 'success',
								mask: true,
								duration: duration
							});
							this.res = '请求结果 : ' + JSON.stringify(res);
						}
					},
					fail(err) {
						if (this.pageVisible) {
							console.log('request fail', err);
							uni.showModal({
								content: err.errMsg,
								showCancel: false
							});
						}
					},
					complete() {
						this.loading = false;
					},
				});
81 82 83
			}
		}
	}
taohebin@dcloud.io's avatar
taohebin@dcloud.io 已提交
84
</script>