欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

uni-app?vue3接口請(qǐng)求封裝示例代碼

 更新時(shí)間:2023年05月03日 09:59:10   作者:搬磚的阿魯  
uni-app是一個(gè)使用Vue.js開(kāi)發(fā)的多端開(kāi)發(fā)框架,下面這篇文章主要給大家介紹了關(guān)于uni-app?vue3接口請(qǐng)求封裝的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下

uni-app接口,全局方法封裝

1.在根目錄創(chuàng)建一個(gè)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 = {
	// 獲取驗(yàn)證碼
	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;  //設(shè)置為 false ,可以阻止 vue 在啟動(dòng)時(shí)生成生產(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' // 請(qǐng)求方式中間件
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.接口請(qǐng)求

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',
	})
}
//校驗(yàn)手機(jī)格式 
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, //默認(rèn)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],//這里是圖片的本地文件路徑列表(選擇圖片成功的時(shí)候可以拿到,在上邊的success回調(diào)中res.tempFilePaths即可拿到)
				name: 'file',//上傳的名字叫啥都行
				// headers: {
				// 	accessToken:'' //可以設(shè)置你的請(qǐng)求頭的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,'上傳結(jié)果');
				}
			})
		}
	});
}

vue3接口請(qǐng)求封裝

1.在項(xiàng)目中安裝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)建一個(gè)axios的對(duì)象
import { useRouter } from "vue-router";
import { inject } from "vue";
//生成一個(gè)axios的實(shí)例
const http=axios.create({
	baseURL:"https://xxxx.test03.qcw800.com",// baseURL會(huì)在發(fā)送請(qǐng)求的時(shí)候拼接在url參數(shù)前面
	timeout:6000,//請(qǐng)求超時(shí)
});
// http.defaults.headers['api_token'] = localStorage.getItem('token') || '' //在請(qǐng)求頭中傳入token
http.interceptors.request.use(config => { 
    // console.log(config,'請(qǐng)求攔截');
  return config;
}, err => { 
  return Promise.reject(err)
})
//響應(yīng)攔截器
http.interceptors.response.use(response => {
	//console.log(response,'響應(yīng)攔截');
	return response;
  }, err => { 
	return Promise.reject(err)
  })
export default http;//導(dǎo)出

 4.api.js文件代碼

//導(dǎo)入request.js
import request from "@/request/index";
//登錄
export const login = (params) => request.get("/api/user/login",{params});
//獲取個(gè)人信息
export const userDetail = (params) => request.get("/api/user/detail",{params});
//方法二 在api文件里出來(lái)異步請(qǐng)求
// export const getCategory=async()=>{
// 	const res=await request.get(`/category/`);
// 	return res.data;
// };

5.接口請(qǐng)求

<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,'個(gè)人信息');
        })
    })
  }
})
</script>

會(huì)了不!!

 等會(huì)還有解決跨域問(wèn)題,代理代碼

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    port: 8080, // 端口號(hào)
    open: false, //配置是否自動(dòng)啟動(dòng)瀏覽器
    https: false,// https:{type:Boolean}是否啟用https
    proxy: {
      // 代理
      "/api": {
        target: "https://xxxx.test03.qcw800.com",     //要代理訪問(wèn)的路徑
        changeOrigin: true,//開(kāi)啟代理:在本地會(huì)創(chuàng)建一個(gè)虛擬服務(wù)端,然后發(fā)送請(qǐng)求的數(shù)據(jù),并同時(shí)接收請(qǐng)求的數(shù)據(jù),這樣服務(wù)端和服務(wù)端進(jìn)行數(shù)據(jù)的交互就不會(huì)有跨域問(wèn)題
        ws: true,//是否啟用websockets,用不到可設(shè)為false
        pathRewrite: {
          "^/api": ""http://這里理解成用'/api'代替target里面的地址,比如我要調(diào)用'http://192.168.0.45:8088/user/getuserlist',直接寫(xiě)'/api/user/getuserlist'即可
        }
      }
    }
  },
})

總結(jié)

到此這篇關(guān)于uni-app vue3接口請(qǐng)求封裝的文章就介紹到這了,更多相關(guān)uni-app vue3接口請(qǐng)求封裝內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論