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')
});