uni-app?vue3接口請求封裝示例代碼
uni-app接口,全局方法封裝
1.在根目錄創(chuàng)建一個api文件,在api文件夾中創(chuàng)建api.js,baseUrl.js和http.js文件
2. baseUrl.js文件代碼
export default "https://XXXX.test03.qcw800.com/api/"
3.http.js文件代碼
export function https(opts, data) { let httpDefaultOpts = { url: opts.url, data: data, method: opts.method, header: opts.method == 'get' ? { 'X-Requested-With': 'XMLHttpRequest', "Accept": "application/json", "Content-Type": "application/json; charset=UTF-8" } : { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, dataType: 'json', } let token = uni.getStorageSync('token'); if (token != undefined && token != null && token != '') { httpDefaultOpts.header.Authorization = 'Bearer ' + token; } let promise = new Promise(function(resolve, reject) { uni.request(httpDefaultOpts).then( (res) => { // console.log(res, '成功') if(res.statusCode == 401){ uni.clearStorageSync(); } resolve(res) } ).catch( (response) => { // console.log(response, '失敗') reject(response) } ) }) return promise }
4.api.js文件代碼
export const rootUrl="https://ssss.test03.qcw800.com"; //其他接口域名 export const baseUrl= rootUrl + "api/"; export const api = { // 獲取驗證碼 guest:{ url: rootUrl + '/api/public/guest', method: 'GET' }, // 登錄 login:{ url: rootUrl + '/api/user/login', method: 'GET' } }
5.在main.js文件中引入接口文件
import App from './App' // #ifndef VUE3 import Vue from 'vue' Vue.config.productionTip = false; //設置為 false ,可以阻止 vue 在啟動時生成生產(chǎn)提示 App.mpType = 'app' const app = new Vue({ ...App }) app.$mount() // #endif // #ifdef VUE3 import { createSSRApp } from 'vue' import { toast, nav, checkMobile, onuploadFile } from '@/api/functions.js' import { api, rootUrl } from '@/api/api.js' // API 鏈接 import { https } from '@/api/http.js' // 請求方式中間件 import navigationBar from '@/components/navigationBar.vue' import publicContext from '@/components/publicContext.vue' export function createApp() { const app = createSSRApp(App) app.component('navigationBar', navigationBar); app.component('publicContext', publicContext); app.config.globalProperties.$toast = toast; app.config.globalProperties.$nav = nav; app.config.globalProperties.$add = add; app.config.globalProperties.$checkMobile = checkMobile; app.config.globalProperties.$isEmpty = isEmpty; app.config.globalProperties.$formatFloat = formatFloat; app.config.globalProperties.$api = api; app.config.globalProperties.$rootUrl = rootUrl; app.config.globalProperties.$http = https; app.config.globalProperties.$imgUrl = 'https://qianchao-sheke.oss-cn-hangzhou.aliyuncs.com/' return { app } } // #endif
6.接口請求
this.$http(this.$api.messageList,{ api_token:uni.getStorageSync('token'), pageSize:10, page:1 }).then(res=>{ console.log(res,'返回參數(shù)'); })
另外,封裝的全局方法,上面第五步在main文件中已經(jīng)引入,
export function toast(title){ uni.showToast({ icon:'none', title:title, position:'bottom', }) } //校驗手機格式 export function checkMobile(mobile){ return RegExp(/^1[34578]\d{9}$/).test(mobile); } export function nav(url,type=0){ if(type == 0){ uni.navigateTo({ url:url }) }else if(type == 1){ uni.switchTab({ url:url }) }else if(type == 3){ uni.navigateBack({ }) }else if(type == 4){ uni.redirectTo({ url: url }); }else if(type == 5){ uni.reLaunch({ url }); } } // 上傳圖片 export function onuploadFile(){ var _this = this; uni.chooseImage({ count: 1, //默認9 sizeType: ['original', 'compressed'], sourceType: ['album', 'camera'], success: (res) => { // console.log(res.tempFilePaths,'圖片的本地文件路徑列表',_this.$rootUrl); uni.uploadFile({ url: _this.$rootUrl +'/api/public/upload',//上傳圖片的地址 filePath: res.tempFilePaths[0],//這里是圖片的本地文件路徑列表(選擇圖片成功的時候可以拿到,在上邊的success回調(diào)中res.tempFilePaths即可拿到) name: 'file',//上傳的名字叫啥都行 // headers: { // accessToken:'' //可以設置你的請求頭的token噢 // }, success(res) { //上傳成功的回調(diào) // console.log('上傳成功',res) var data = JSON.parse(res.data); return data.data[0]; }, fail(err){ console.log(err,'上傳失敗'); }, complete(result){ console.log(result,'上傳結果'); } }) } }); }
vue3接口請求封裝
1.在項目中安裝axios
npm install --save axios vue-axios
2.在src文件夾下創(chuàng)建request文件夾,及index.js和api.js文件
3.index.js文件代碼
import axios from "axios";//創(chuàng)建一個axios的對象 import { useRouter } from "vue-router"; import { inject } from "vue"; //生成一個axios的實例 const http=axios.create({ baseURL:"https://xxxx.test03.qcw800.com",// baseURL會在發(fā)送請求的時候拼接在url參數(shù)前面 timeout:6000,//請求超時 }); // http.defaults.headers['api_token'] = localStorage.getItem('token') || '' //在請求頭中傳入token http.interceptors.request.use(config => { // console.log(config,'請求攔截'); return config; }, err => { return Promise.reject(err) }) //響應攔截器 http.interceptors.response.use(response => { //console.log(response,'響應攔截'); return response; }, err => { return Promise.reject(err) }) export default http;//導出
4.api.js文件代碼
//導入request.js import request from "@/request/index"; //登錄 export const login = (params) => request.get("/api/user/login",{params}); //獲取個人信息 export const userDetail = (params) => request.get("/api/user/detail",{params}); //方法二 在api文件里出來異步請求 // export const getCategory=async()=>{ // const res=await request.get(`/category/`); // return res.data; // };
5.接口請求
<script> import { defineComponent,onMounted } from 'vue' import { userDetail } from '@/request/api' export default defineComponent({ setup() { onMounted(()=>{ userDetail({api_token:localStorage.getItem('token')}).then(res=>{ console.log(res,'個人信息'); }) }) } }) </script>
會了不!!
等會還有解決跨域問題,代理代碼
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, devServer: { port: 8080, // 端口號 open: false, //配置是否自動啟動瀏覽器 https: false,// https:{type:Boolean}是否啟用https proxy: { // 代理 "/api": { target: "https://xxxx.test03.qcw800.com", //要代理訪問的路徑 changeOrigin: true,//開啟代理:在本地會創(chuàng)建一個虛擬服務端,然后發(fā)送請求的數(shù)據(jù),并同時接收請求的數(shù)據(jù),這樣服務端和服務端進行數(shù)據(jù)的交互就不會有跨域問題 ws: true,//是否啟用websockets,用不到可設為false pathRewrite: { "^/api": ""http://這里理解成用'/api'代替target里面的地址,比如我要調(diào)用'http://192.168.0.45:8088/user/getuserlist',直接寫'/api/user/getuserlist'即可 } } } }, })
總結
到此這篇關于uni-app vue3接口請求封裝的文章就介紹到這了,更多相關uni-app vue3接口請求封裝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
項目遷移vite引入圖片資源報require?is?not?defined問題的解決辦法
這篇文章主要給大家介紹了關于項目遷移vite引入圖片資源報require?is?not?defined問題的解決辦法,文中通過代碼介紹的非常詳細,對大家學習或者使用vite具有一定的參考借鑒價值,需要的朋友可以參考下2024-01-01Vue Element前端應用開發(fā)之整合ABP框架的前端登錄
VUE+Element 前端是一個純粹的前端處理,前面介紹了很多都是Vue+Element開發(fā)的基礎,從本章隨筆開始,就需要進入深水區(qū)了,需要結合ABP框架使用2021-05-05解決element-ui的table表格控件表頭與內(nèi)容列不對齊問題
這篇文章主要介紹了解決element-ui的table表格控件表頭與內(nèi)容列不對齊問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07