Rumah >hujung hadapan web >View.js >Bagaimana untuk merangkum permintaan antara muka vue3 uni-app

Bagaimana untuk merangkum permintaan antara muka vue3 uni-app

WBOY
WBOYke hadapan
2023-05-11 19:28:102425semak imbas

antara muka uni-app, enkapsulasi kaedah global

1 Cipta fail api dalam direktori akar dan buat fail api.js, baseUrl.js dan http.js dalam folder api

<.>

Bagaimana untuk merangkum permintaan antara muka vue3 uni-app

2. kod fail baseUrl.js

export default "https://XXXX.test03.qcw800.com/api/"

Kod fail 3.http.js

export function https(opts, data) {
	let httpDefaultOpts = {
		url: opts.url,
		data: data,
		method: opts.method,
		header: opts.method == &#39;get&#39; ? {
			&#39;X-Requested-With&#39;: &#39;XMLHttpRequest&#39;,
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			&#39;X-Requested-With&#39;: &#39;XMLHttpRequest&#39;,
			&#39;Content-Type&#39;: &#39;application/x-www-form-urlencoded; charset=UTF-8&#39;
		},
		dataType: &#39;json&#39;,
	}
	let token = uni.getStorageSync(&#39;token&#39;);
	if (token != undefined && token != null && token != &#39;&#39;) {
		httpDefaultOpts.header.Authorization = &#39;Bearer &#39; + token;
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				// console.log(res, &#39;成功&#39;)
				if(res.statusCode == 401){
					uni.clearStorageSync();
				}
				resolve(res)
			}
		).catch(
			(response) => {
				// console.log(response, &#39;失败&#39;)
				reject(response)
			}
		)
	})
	return promise
}

kod fail 4.api.js

export const rootUrl="https://ssss.test03.qcw800.com";  //其他接口域名
export const baseUrl= rootUrl + "api/";
export const api = {
	// 获取验证码
	guest:{ 
		url: rootUrl + &#39;/api/public/guest&#39;,
		method: &#39;GET&#39;
	},
	// 登录
	login:{  
		url: rootUrl + &#39;/api/user/login&#39;,
		method: &#39;GET&#39;
	}
}

5. Perkenalkan fail antara muka

import App from &#39;./App&#39;
// #ifndef VUE3
import Vue from &#39;vue&#39;
Vue.config.productionTip = false;  //设置为 false ,可以阻止 vue 在启动时生成生产提示
App.mpType = &#39;app&#39;
const app = new Vue({
	...App
})
app.$mount()
// #endif
// #ifdef VUE3
import {
	createSSRApp
} from &#39;vue&#39;
import {
	toast,
	nav,
	checkMobile,
	onuploadFile
} from &#39;@/api/functions.js&#39;
import {
	api,
	rootUrl
} from &#39;@/api/api.js&#39; // API 链接
import {
	https
} from &#39;@/api/http.js&#39; // 请求方式中间件
import navigationBar from &#39;@/components/navigationBar.vue&#39;
import publicContext from &#39;@/components/publicContext.vue&#39;
export function createApp() {
	const app = createSSRApp(App)
	app.component(&#39;navigationBar&#39;, navigationBar);
	app.component(&#39;publicContext&#39;, 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 = &#39;https://qianchao-sheke.oss-cn-hangzhou.aliyuncs.com/&#39;
	return {
		app
	}
}
// #endif

dalam fail utama.js 6. Permintaan antara muka

this.$http(this.$api.messageList,{
					api_token:uni.getStorageSync(&#39;token&#39;),
					pageSize:10,
                    page:1
				}).then(res=>{
					console.log(res,&#39;返回参数&#39;);
				})

Selain itu, kaedah global yang dirangkumkan, langkah kelima di atas telah diperkenalkan dalam fail utama,

export function toast(title){
	uni.showToast({
		icon:&#39;none&#39;,
		title:title,
		position:&#39;bottom&#39;,
	})
}
//校验手机格式 
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: [&#39;original&#39;, &#39;compressed&#39;],
		sourceType: [&#39;album&#39;, &#39;camera&#39;],
		success: (res) => {
			// console.log(res.tempFilePaths,&#39;图片的本地文件路径列表&#39;,_this.$rootUrl);
			uni.uploadFile({
				url: _this.$rootUrl +&#39;/api/public/upload&#39;,//上传图片的地址
				filePath: res.tempFilePaths[0],//这里是图片的本地文件路径列表(选择图片成功的时候可以拿到,在上边的success回调中res.tempFilePaths即可拿到)
				name: &#39;file&#39;,//上传的名字叫啥都行
				// headers: {
				// 	accessToken:&#39;&#39; //可以设置你的请求头的token噢
				// },
				success(res) {
					//上传成功的回调
					// console.log(&#39;上传成功&#39;,res)
					var data = JSON.parse(res.data);
					return data.data[0];
				},
				fail(err){
					console.log(err,&#39;上传失败&#39;);
				},
				complete(result){
					console.log(result,&#39;上传结果&#39;);
				}
			})
		}
	});
}

enkapsulan permintaan antara muka vue3

1 Pasang axios dalam projek

npm install --save axios vue-axios

2. Cipta folder permintaan, index.js dan api.js dalam folder src Fail

Bagaimana untuk merangkum permintaan antara muka vue3 uni-app

Kod fail 3.index.js

import axios from "axios";//创建一个axios的对象
import { useRouter } from "vue-router";
import { inject } from "vue";
//生成一个axios的实例
const http=axios.create({
	baseURL:"https://xxxx.test03.qcw800.com",// baseURL会在发送请求的时候拼接在url参数前面
	timeout:6000,//请求超时
});
// http.defaults.headers[&#39;api_token&#39;] = localStorage.getItem(&#39;token&#39;) || &#39;&#39; //在请求头中传入token
http.interceptors.request.use(config => { 
    // console.log(config,&#39;请求拦截&#39;);
  return config;
}, err => { 
  return Promise.reject(err)
})
//响应拦截器
http.interceptors.response.use(response => {
	//console.log(response,&#39;响应拦截&#39;);
	return response;
  }, err => { 
	return Promise.reject(err)
  })
export default http;//导出

4.api.js kod fail

//导入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 &#39;vue&#39;
import { userDetail } from &#39;@/request/api&#39;
export default defineComponent({
  setup() {
    onMounted(()=>{
      userDetail({api_token:localStorage.getItem(&#39;token&#39;)}).then(res=>{
            console.log(res,&#39;个人信息&#39;);
        })
    })
  }
})
</script>

Ya! !

Kami akan menyelesaikan masalah merentas domain kemudian, kod proksi

const { defineConfig } = require(&#39;@vue/cli-service&#39;)
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,//开启代理:在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
        ws: true,//是否启用websockets,用不到可设为false
        pathRewrite: {
          "^/api": ""//这里理解成用&#39;/api&#39;代替target里面的地址,比如我要调用&#39;http://192.168.0.45:8088/user/getuserlist&#39;,直接写&#39;/api/user/getuserlist&#39;即可
        }
      }
    }
  },
})

Atas ialah kandungan terperinci Bagaimana untuk merangkum permintaan antara muka vue3 uni-app. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Artikel ini dikembalikan pada:yisu.com. Jika ada pelanggaran, sila hubungi admin@php.cn Padam