nuxt3 useFetch请求封装

nuxt3 useFetch请求封装
首先在composables文件下新建http.js文件,composables文件下不需要引入

import { showToast, showLoadingToast } from 'vant';
import store from "@/store"
const request = async (url, options) => {
	await nextTick(); //解决刷新页面useFetch无返回
	const config = useRuntimeConfig();
	const reqUrl = config.public.apiBase + url;
	const customHeaders = {"APP-TOKEN": `${store.state.token}`, "Content-Type": "application/json" }
	// console.log(reqUrl,'reqUrl')
	console.log('options:--',options)
	// console.log('headers:',headers)
	// const options=options||''
	return new Promise((resolve, reject) => {
		useFetch(reqUrl, { ...options, headers:customHeaders}).then(({ data, error }) => {
				console.log(data,'data')
				if (error.value) {
					reject(error.value);
					return;
				}
				const value = data.value;
				if (!value) {
					console.log("执行错误了");
				} else if(value.code === 200) {
					resolve(value);
				}else{
					showToast(value.errMsg)
				}
			})
			.catch((err) => {
				reject(err);
			});
	});
};
export const http = {
	get: (url, query, headers) => {
		return request(url, { method: 'GET', query  },headers);
	},
	post: (url, body, headers) => {
		return request(url, { method: 'POST', body },headers);
	},
}
//get请求
http.get('/memberTotal').then(res => {
        if (res.code == 200) {
          
        }
      }).catch((err) => {
        console.log(err, 'err')
      });
//post请求
 let obj = {
        phone: this.phoneValue,
        smsCode: this.codeValue,
        inviteCode: this.token||'',
      };
      http.post('/registerBySms',obj).then(res => {
        if (res.code == 200) {
          localStorage.setItem("BGS_TOKEN", res.data.token)
          this.showLoading = true;
          this.$router.push("/download");
        }
      }).catch((err) => {
        console.log(err, 'err')
      });
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值