uView框架1.0拦截器相关参数设置

1、拦截器 http.interceptor.js

// 参考地址:https://www.uviewui.com/js/http.html
import config from './config.js';

const install = (Vue, vm) => {
	// 此为自定义配置参数,具体参数见上方说明
	Vue.prototype.$u.http.setConfig({
		baseUrl: config.baseUrl, // 请求的本域名
		method: 'POST',
		dataType: 'json', // 设置为json,返回后会对数据进行一次JSON.parse()
		showLoading: false, // 是否显示请求中的loading
		loadingText: '请求中...', // 请求loading中的文字提示
		loadingTime: 800, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
		originalData: false, // 是否在拦截器中返回服务端的原始数据
		loadingMask: true, // 展示loading的时候,是否给一个透明的蒙层,防止触摸穿透
		// 配置请求头信息
		header: {
			'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
			// 'content-Type': 'application/json',
		},
	});

	// 请求拦截,配置Token等参数
	Vue.prototype.$u.http.interceptor.request = (config) => {
		// 获取token
		const token = uni.getStorageSync('token');
		uni.setStorageSync('token',token);
		
		// 获取设备端类型
		const os = uni.getStorageSync('os');
		// console.log("==获取设备端类型==")
		// console.log(os);

		// 参数
		config.header['token'] = token || '';
		config.header['os'] = os || '';

		return config;
	}

	// 响应拦截,判断状态码是否通过
	Vue.prototype.$u.http.interceptor.response = (res) => {
		// console.log("==响应拦截==")
		// console.log(res)
		if (res.code == 0) {
			// res为服务端返回值,可能有code,result等字段
			// 这里对res.result进行返回,将会在this.$u.post(url).then(res => {})的then回调中的res的到
			// 如果配置了originalData为true,请留意这里的返回值
			return res;
		} else if (res.code == 401) {
			// 401为token失效
			uni.setStorageSync('token', ''); // 缓存token
			vm.$u.toast(res.msg);
			setTimeout(() => {
				vm.$u.route('/pages/login/login')
			}, 1500)
			return false;
		} else if (res.code == 405) {
			// 405为token为空
			vm.$u.toast(res.msg);
			setTimeout(() => {
				vm.$u.route('/pages/login/login')
			}, 1500)
			return false;
		} else if (res.code == 1) {
			vm.$u.toast(res.msg);
			return false;
		} else {
			// 如果返回false,则会调用Promise的reject回调,
			// 并将进入this.$u.post(url).then().catch(res=>{})的catch回调中,res为服务端的返回值
			return false;
		}

	}
}

export default {
	install
}

2、修改post请求的临时参数格式为json

_this.$u.post('接口名称', {
	xingming: formData.xingming,
	tel: formData.tel,
	info: formData.info,
}, {
	'content-Type': 'application/json',
}).then(res => {
	console.log("==提交私人定制==");
	console.log(res);
	uni.showToast({
		title: res.msg,
	});
	setTimeout(function() {
		uni.navigateBack({
			delta: 1
			})
		}, 2000)
	}).catch(res => {
		console.log(res);
})

你可能感兴趣的:(uniapp,javascript)