uniapp封装ajax请求

新建一个request.js

import '@/common/api/interceptor.js'; // 引入拦截器文件
export default{
	common:{
		baseUrl:"http://localhost:3000/api",
		data:{},
		header:{
			"Access-Control-Allow-Origin":"*",
			"Content-Type":"application/json",
			"Content-Type":"application/x-www-form-urlencoded"
		},
		method:"GET",
		dataType:"json"
	},
	//封装为选项对象
	request( options={} ){
		
		uni.showLoading({
		    title: '加载中'
		});
		
		options.url = this.common.baseUrl + options.url;
		options.data = 	options.data || this.common.data;
		options.header = options.header || this.common.header;
		options.method = options.method || this.common.method;
		options.dataType = 	options.dataType || this.common.dataType;
		return new Promise((res,rej)=>{
			uni.request({
				...options,
				success: (result) => {
					// if(result.statusCode===401)  进行类似过滤器的操作
					if(result.statusCode != 200){
						// 使其可以使用catch
						return rej();
					}
					setTimeout(function () {
					    uni.hideLoading();
					}, 1500);
					let data = result.data;
					// res里面就是请求体了 可以直接获取自己定义的code 和数据
					res(data);
				}
			})
		})
	}
}

这样就把uniapp的回调ajax封装为了resolve,这里还类似封装了axios的拦截器

// utils/interceptors.js



// 请求拦截器
uni.addInterceptor('request', {
  // 在发送请求之前执行
  invoke(request) {
    // 在请求发送前可以进行一些操作,例如添加请求头、设置认证信息等

	    request.header = {
	      'Content-Type': 'application/json', // 设置 Content-Type 请求头
	      'Authorization': 'Bearer your-token', // 设置 Authorization 请求头
	    };
    console.log('------请求拦截器------');
    return request;
  },
  // 请求出错时执行
  fail(error) {
    console.error('请求拦截器出错', error);
    return error;
  },
});

// 响应拦截器
uni.addInterceptor('response', {
  // 在响应返回之后执行
  invoke(response) {
    // 对响应数据进行处理
    console.log('响应拦截器');
	response.header={
		"Access-Control-Allow-Origin":"*"
	}
    return response;
  },
  // 响应出错时执行
  fail(error) {
    console.error('响应拦截器出错', error);
    return error;
  },
});

在其他compoent的js中使用

import http from '@/common/api/request.js';
//初始化
var init=()=>{
	http.request({url:"/index_list/data",
	}).then(res=>{
		console.log("封装的结果",res),
		topBar.value=res.data.topBar
	}).catch(e=>{
		console.log(e)
	})
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝胖子不是胖子

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

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

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

打赏作者

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

抵扣说明:

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

余额充值