基于根目录创建文件
config.js
// 系统信息
export const SYSTEM_INFO = uni.getSystemInfoSync()
// 主机地址
export const HOST = '';
// api服务器
export const API_HOST = SYSTEM_INFO.uniPlatform === 'web' ? '' : HOST;
// api服务代理路径
export const API_PROXY = SYSTEM_INFO.uniPlatform === 'web' ? '/h5api' : ''
utils/common.js
import {API_HOST,API_PROXY} from "../config.js"
/**
* 组装接口url
*/
export const packApiUrl = (url = '') => {
if (url.slice(0, 4) === 'http') return url
else return `${API_HOST}${API_PROXY}${url}`
}
utils/request.js
import {packApiUrl} from "./common.js"
export function request(config={}){
let {
url,
data={},
method="GET",
header={}
} = config
url =packApiUrl(url);
header['Token'] = uni.getStorageSync("userToken")
return new Promise((resolve,reject)=>{
uni.request({
url,
data,
method,
header,
success:res=>{
if(res.data.code==0){
resolve(res)
}else if(res.data.code==401){
uni.navigateTo({
url:'/pages/index'
})
}else{
uni.showToast({
title:res.data.msg,
icon:"none"
})
reject(res.data)
}
},
fail:err=>{
reject(err)
}
})
})
}
api/api.js
import { request } from '../utils/request.js'
/* POST */
export function apiLogin(){
return request({
url:"/login",
method:"POST"
})
}
/* POST传参 */
export function apiLogin(data={}){
return request({
url:"/login",
method:"POST",
data
})
}
/* GET */
export function apiLogin(data={}){
return request({
url:"/login",
method:"POST",
data
})
}
/* GET无参 */
export function apiLogin(){
return request({
url:"/login",
})
}
pages/index.vue
import { apiLogin } from '../../api/apis.js';
const data = {
user:user.value,
pass:pass.value
}
const LoginThred= async() =>{
let res = await apiLogin(data).then(res=>{
console.log('res',res)
//执行交互
});
}
跨域执行,非内置浏览器访问
vite.config.js
import { defineConfig } from "vite"
import uni from '@dcloudio/vite-plugin-uni'
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
uni(),
// 自动导入配置
AutoImport({
imports:[
// 预设
"vue",
"uni-app"
]
})
],
server: {
host: "localhost", // 指定服务器应该监听哪个IP地址,默认:localhost
port: 5173, // 指定开发服务器端口,默认:5173
proxy: { // 为开发服务器配置自定义代理规则
// 带选项写法:http://localhost:5173/api/posts -> http://jsonplaceholder.typicode.com/posts
"/h5api": {
target: "", // 目标接口
changeOrigin: true, // 是否换源
rewrite: (path) => path.replace(/^\/h5api/, ""),
}
}
}
})