feat: 接口请求

This commit is contained in:
Tony 2024-03-26 09:37:50 +08:00
parent c9093605d0
commit 8c4e9a416a
8 changed files with 173 additions and 129 deletions

View File

@ -2,7 +2,8 @@
"description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html", "description": "项目私有配置文件。此文件中的内容将覆盖 project.config.json 中的相同字段。项目的改动优先同步到此文件中。详见文档https://developers.weixin.qq.com/miniprogram/dev/devtools/projectconfig.html",
"projectname": "taro-demo", "projectname": "taro-demo",
"setting": { "setting": {
"compileHotReLoad": true "compileHotReLoad": true,
"urlCheck": false
}, },
"condition": {} "condition": {}
} }

View File

@ -1,5 +1,5 @@
import { Image, View } from "@tarojs/components"; import { Image, View } from "@tarojs/components";
import { useState } from "react"; import { useEffect, useState } from "react";
import Taro from "@tarojs/taro"; import Taro from "@tarojs/taro";
import Iot from "../iot"; import Iot from "../iot";
@ -17,6 +17,15 @@ import tab3Icon from '../../assets/images/tab/tab3.png'
import tab3Icon_selected from '../../assets/images/tab/tab3_selected.png' import tab3Icon_selected from '../../assets/images/tab/tab3_selected.png'
import { globalData } from "../../config"; import { globalData } from "../../config";
import { request } from "../../config/axios";
const getDevice = (data) => {
return request({
url: '/app/soil-insect/getDevice',
method: 'GET',
data
})
}
const Index = () => { const Index = () => {
// Taro.navigateTo({ url: '/pages/inspectionLog/index' }) // Taro.navigateTo({ url: '/pages/inspectionLog/index' })
@ -34,6 +43,14 @@ const Index = () => {
} }
handleAuth() handleAuth()
useEffect(() => {
getDevice({
belongPark: '1769896538700668928',
belongPlot: '1769908355099721729',
deviceType: '14,16'
})
}, [])
const bottomMenuList = [ const bottomMenuList = [
{ {
id: 'iot', id: 'iot',
@ -59,7 +76,7 @@ const Index = () => {
] ]
return ( return (
<View className="h-[100vh] flex flex-col-reverse relative bg-slate-50"> <View className="h-[100vh] flex flex-col-reverse relative bg-slate-50" onTouchMove={(e) => { e.stopPropagation() }}>
<Image src={basicBg} className="absolute z-0 top-0 w-full"></Image> <Image src={basicBg} className="absolute z-0 top-0 w-full"></Image>
<View className="flex justify-evenly align-top relative z-100 bg-white" style={{ height: globalData.navigatorHeight + 'px' }}> <View className="flex justify-evenly align-top relative z-100 bg-white" style={{ height: globalData.navigatorHeight + 'px' }}>
{ {

View File

@ -1,5 +1,5 @@
import { View } from "@tarojs/components" import { View } from "@tarojs/components"
// import './index.css' import './index.css'
/** /**
* options selected为选中值 callback为函数回调 * options selected为选中值 callback为函数回调

View File

@ -1,6 +0,0 @@
export default {
'401': '认证失败,无法访问系统资源',
'403': '当前操作没有权限',
'404': '访问资源不存在',
default: '系统未知错误,请反馈给管理员'
}

View File

@ -0,0 +1,38 @@
import Taro from "@tarojs/taro"
import { axiosConfig } from ".."
import { stringify } from "qs"
export const request = ({
url = '',
baseUrl = axiosConfig.baseUrl,
data = {},
method = 'GET',
header = {
'Authorization': Taro.getStorageSync('token')
}
}): Promise<any> => {
let requestParams = '?'
if (method === 'GET') requestParams += stringify(data, { indices: false })
console.log('requestParams', requestParams);
return new Promise((resolve, reject) => {
Taro.showLoading({ title: '加载中...' })
Taro.request({
url: baseUrl + url + (requestParams === '?' ? '' : requestParams),
data,
method: method as any,
header,
success: function (res) {
console.log('接口返回', res);
resolve(res.data)
},
fail: function(err) {
console.error('err', err);
reject(err)
},
complete: function () {
Taro.hideLoading()
}
})
})
}

View File

@ -1,109 +0,0 @@
import axios, { AxiosError, AxiosInstance, AxiosRequestHeaders, AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { axiosConfig } from "..";
import Taro from "@tarojs/taro";
import qs from 'qs'
import errorCode from './errorCode'
// 请求白名单无须token的接口
const whiteList: string[] = ['/login', '/refresh-token']
// 是否正在刷新中
let isRefreshToken = false
// 请求队列
let requestList: any[] = []
// 创建实例
const service: AxiosInstance = axios.create({
baseURL: axiosConfig.baseUrl,
timeout: axiosConfig.timeout,
withCredentials: axiosConfig.withCredentials
});
const getAccessToken = () => {
return Taro.getStorageSync('token')
}
// request拦截器
service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
// 是否需要设置 token
let isToken = (config!.headers || {}).isToken === false
whiteList.some((v) => {
if (config.url) {
config.url.indexOf(v) > -1
return (isToken = false)
}
})
if (getAccessToken() && !isToken) {
; (config as any).headers.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token
}
const params = config.params || {}
const data = config.data || false
if (
config.method?.toUpperCase() === 'POST' &&
(config.headers as AxiosRequestHeaders)['Content-Type'] ===
'application/x-www-form-urlencoded'
) { config.data = qs.stringify(data) }
// get参数编码
if (config.method?.toUpperCase() === 'GET' && params) {
config.params = {}
const paramsStr = qs.stringify(params, { allowDots: true })
if (paramsStr) {
config.url = config.url + '?' + paramsStr
}
}
return config
}, (error: AxiosError) => {
Promise.reject(error)
})
// response 拦截器
service.interceptors.response.use(
async (response: AxiosResponse<any>) => {
let { data } = response
const config = response.config
if (!data) { throw new Error() }
const code = data.code || 200 // 默认成功
// 获取错误信息
const msg = data.msg || errorCode[code] || errorCode['default']
if (code === 401) {
// 如果未认证,并且未进行刷新令牌,说明可能是访问令牌过期了
// isRefreshToken false 未开始刷新token 进入刷新token程序
if (!isRefreshToken) {
isRefreshToken = true
try {
// 使用默认的用户名密码进行登录操作
const token = 'request login'
Taro.setStorageSync('token', token)
config.headers!.Authorization = 'Bearer ' + getAccessToken()
requestList.forEach((cb: any) => { cb() })
requestList = []
return service(config)
} catch (e) {
// 刷新失败时 处理错误
requestList = [] // 清空队列
return Promise.reject()
} finally {
requestList = []
isRefreshToken = false
}
} else {
// 正在尝试刷新token放入等待队列
return new Promise((resolve) => {
requestList.push(() => {
config.headers!.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token 请根据实际情况自行修改
resolve(service(config))
})
})
}
} else if (code === 500) {
return Promise.reject(new Error(msg))
} else {
return data
}
}
)

View File

@ -1,5 +1,5 @@
export const axiosConfig = { export const axiosConfig = {
baseUrl: '', baseUrl: 'http://117.73.12.97:1606/admin-api/',
timeout: 30000, timeout: 30000,
withCredentials: false // 禁用 Cookie 等信息 withCredentials: false // 禁用 Cookie 等信息
} }

View File

@ -3,23 +3,104 @@ import loginBg from '../../assets/images/loginBg.png'
import questionIcon from '../../assets/images/icons/question-line.png' import questionIcon from '../../assets/images/icons/question-line.png'
import Taro from "@tarojs/taro" import Taro from "@tarojs/taro"
import { useState } from "react" import { useState } from "react"
import { request } from "../../config/axios"
const login = (data, tenantId = '1') => {
return request({
url: '/system/auth/login',
method: 'POST',
header: { 'Tenant-Id': tenantId },
data
})
}
const getTenantId = (data) => {
return request({
url: '/system/tenant/get-id-by-name',
method: 'GET',
data
})
}
const autoLoginCheck = async () => {
const expireTime = Taro.getStorageSync('expiresTime')
const nowTime = new Date().valueOf()
console.log('expireTime', expireTime);
if (expireTime) {
if (expireTime - nowTime > 1000 * 60 * 60 * 8) {
// 过期时间大于八小时
Taro.redirectTo({ url: '/basePage/index/index' })
} else {
// 过期时间不足 八小时
const tenantName = Taro.getStorageSync('tenantName')
if (!tenantName) return
const { data: _tenantId } = await getTenantId({ name: tenantName })
if (!_tenantId) return;
const password = Taro.getStorageSync('password')
const username = Taro.getStorageSync('username')
const { data } = await login({
password,
rememberMe: true,
tenantName,
username
}, _tenantId.toString())
if (data.accessToken) {
Taro.setStorageSync('token', data.accessToken)
Taro.hideLoading()
Taro.redirectTo({ url: '/basePage/index/index' })
}
}
}
}
const Login = () => { const Login = () => {
const [username, setUserName] = useState('') const [username, setUserName] = useState('')
const [password, setPassWord] = useState('') const [password, setPassWord] = useState('')
const handleLogin = () => { const [tenantName, setTenantName] = useState('')
if (!username || !password) return const handleLogin = async () => {
Taro.setStorageSync('username', username) if (!username || !password) {
Taro.setStorageSync('password', password) Taro.showModal({
// 请求完成后跳转 title: '提示',
Taro.showLoading({ title: '加载中...'}) content: '请输入完整的用户名和密码!',
setTimeout(() => { success: function (res) {
Taro.setStorageSync('token', 'testToken') if (res.confirm) {
Taro.hideLoading() console.log('用户点击确定')
Taro.redirectTo({ url: '/basePage/index/index' }) } else if (res.cancel) {
}, 2000) console.log('用户点击取消')
}
}
})
return
} }
Taro.setStorageSync('username', username)
Taro.setStorageSync('password', password)
Taro.setStorageSync('tenantName', tenantName)
Taro.showLoading({ title: '加载中...'})
const { data: _tenantId } = await getTenantId({ name: tenantName })
if (!_tenantId) return;
const { data } = await login({
password,
rememberMe: true,
tenantName,
username
}, _tenantId.toString())
if (data.accessToken) {
Taro.setStorageSync('token', data.accessToken)
Taro.hideLoading()
Taro.redirectTo({ url: '/basePage/index/index' })
}
if (data.expiresTime) {
Taro.setStorageSync('expiresTime', data.expiresTime)
}
}
autoLoginCheck()
return ( return (
<View className="w-full h-[100vh] relative"> <View className="w-full h-[100vh] relative">
<Image src={loginBg} className="w-full h-full" /> <Image src={loginBg} className="w-full h-full" />
@ -30,7 +111,17 @@ const Login = () => {
<View className="text-slate-800 font-bold text-2xl px-6 pt-3"> <View className="text-slate-800 font-bold text-2xl px-6 pt-3">
</View> </View>
<View className="w-[100vw] mt-7 p-3 bg-white rounded-md"> <View className="w-[94vw] ml-[3vw] mt-7 p-4 bg-white rounded-xl shadow-xl">
<View className="p-2">
<View></View>
<View className=" border-b-2 border-slate-400 py-2">
<Input
type="text"
placeholder="请输入租户名"
onInput={(_tenantName) => setTenantName((_tenantName.target as any).value)}
></Input>
</View>
</View>
<View className="p-2"> <View className="p-2">
<View></View> <View></View>
<View className=" border-b-2 border-slate-400 py-2"> <View className=" border-b-2 border-slate-400 py-2">
@ -52,7 +143,19 @@ const Login = () => {
</View> </View>
</View> </View>
<View className="flex flex-row-reverse p-1"> <View className="flex flex-row-reverse p-1">
<View className="flex items-center"> <View className="flex items-center" onClick={() => {
Taro.showModal({
title: '提示',
content: '请联系管理员重置密码!',
success: function (res) {
if (res.confirm) {
console.log('用户点击确定')
} else if (res.cancel) {
console.log('用户点击取消')
}
}
})
}}>
<Image src={questionIcon} className="w-[1.1rem] h-[1.1rem]"></Image> <Image src={questionIcon} className="w-[1.1rem] h-[1.1rem]"></Image>
<Text className="text-[1rem] p-1" style={{ color: '#0fc87c' }}>?</Text> <Text className="text-[1rem] p-1" style={{ color: '#0fc87c' }}>?</Text>
</View> </View>