Commit d5e220ce by lirandong

添加 网络请求和token相关功能

parent 6f48c857
...@@ -42,6 +42,7 @@ ...@@ -42,6 +42,7 @@
"@tarojs/taro-swan": "1.3.12", "@tarojs/taro-swan": "1.3.12",
"@tarojs/taro-tt": "1.3.12", "@tarojs/taro-tt": "1.3.12",
"@tarojs/taro-weapp": "1.3.12", "@tarojs/taro-weapp": "1.3.12",
"axios": "^0.19.0",
"nerv-devtools": "^1.4.0", "nerv-devtools": "^1.4.0",
"nervjs": "^1.4.0", "nervjs": "^1.4.0",
"react": "16.3.1", "react": "16.3.1",
...@@ -58,6 +59,7 @@ ...@@ -58,6 +59,7 @@
"@tarojs/plugin-uglifyjs": "1.3.12", "@tarojs/plugin-uglifyjs": "1.3.12",
"@tarojs/webpack-runner": "1.3.12", "@tarojs/webpack-runner": "1.3.12",
"@types/react": "^16.4.8", "@types/react": "^16.4.8",
"@types/react-native": "^0.60.3",
"@types/webpack-env": "^1.13.6", "@types/webpack-env": "^1.13.6",
"@typescript-eslint/parser": "^1.6.0", "@typescript-eslint/parser": "^1.6.0",
"babel-eslint": "^8.2.3", "babel-eslint": "^8.2.3",
......
// import users from '@api/users'
// import { concatParam } from '@/utils/utils'
import { concatParam } from '../constants/utils'
// import $config, { message, requestCode, tokens } from '@/config'
import axios, { CancelTokenStatic, AxiosInstance } from 'axios'
import { BASE_URL, FETCH_TIME_OUT, INTERFACE_REPEAT } from 'src/constants/counter'
const concatParamMethod = new Set(['post', 'put'])
// let refreshTokenState = false // 刷新 token的状态
const FetchSet: Set<string> = new Set() // 防重复容器
const CancelToken: CancelTokenStatic = axios.CancelToken // 取消请求类
const $axios: AxiosInstance = axios.create({
baseURL: BASE_URL,
timeout: FETCH_TIME_OUT
})
// 请求拦截器
$axios.interceptors.request.use((config: any) => {
const { repeat, noToken } = config.headers
// 设置token
if (!noToken) {
// 默认添加token
// config.headers.token = tokens.getToken()
} else {
delete config.headers.noToken
}
// 防重复设置
if (!repeat) {
// 默认开启防重复请求
config.FetchKey = config.url
// 根据请求方法是否要整合参数
const method = config.method.toLocaleLowerCase()
if (concatParamMethod.has(method))
config.FetchKey = `${config.FetchKey}?${concatParam(config.data)}`
if (FetchSet.has(config.FetchKey)) {
// 接口重复请求
config.cancelToken = new CancelToken(cancel => {
console.warn(`接口重复,已取消接口 ${config.url} 的重复请求`)
cancel(INTERFACE_REPEAT)
})
return config
}
FetchSet.add(config.FetchKey) // 添加请求key到防重复容器
delete config.headers.repeat // 删除标识
}
return config
})
// 返回体拦截器
$axios.interceptors.response.use(
async (config: any) => {
// 删除防重复容器里对应的 Key
FetchSet.delete(config.config.FetchKey)
// token过期处理
const { data } = config
if (!data || !data.code) return Promise.reject(config)
const { code } = data
if (code === '0') {
// 正确请求
return data
// } else if (code === requestCode.TOKNE_EXPIRED) {
// // token失效重新请求
// try {
// await refreshToken()
// return $axios.request(config) // token刷新成功重新发起请求
// } catch (error) {
// return Promise.reject(config)
// }
} else {
// 请求出现错误
return Promise.reject(config.data)
}
},
async (error: any) => {
const { config } = error
if (config && config.FetchKey) {
// 取消当前接口的防重复请求限制
FetchSet.delete(config.FetchKey)
}
return Promise.reject(error)
}
)
// async function refreshToken() {
// let refresh
// if (refreshTokenState) return refresh
// refreshTokenState = true
// refresh = await tokens.tryRefreshToken()
// refreshTokenState = false
// return refresh
// }
export default $axios
import axios from './axios'
import { AxiosRequestConfig, AxiosPromise, Method } from 'axios'
interface IRequest {
data: any
url: string
method: Method
config?: AxiosRequestConfig
}
export class ApiClient {
request({ url, config, method = 'POST', data = {} }: IRequest): AxiosPromise<any> {
return axios({
url,
data,
method,
...config
})
}
}
export default new ApiClient()
import user from './users'
export default {
user
}
import { ApiClient } from './client'
class UsersApi extends ApiClient {}
export default new UsersApi()
import '@tarojs/async-await' import '@tarojs/async-await'
import Taro, { Component, Config } from '@tarojs/taro' import configStore from './store'
import { Provider } from '@tarojs/redux' import { Provider } from '@tarojs/redux'
import { pages, INDEX, LOGIN } from './constants/router'
import Taro, { Component, Config } from '@tarojs/taro'
import Index from './pages/index' import Index from './pages/index'
// import Login from './pages/login'
import configStore from './store' // import './app.less'
import token from './constants/token'
import './app.less' // import api from './api';
// 如果需要在 h5 环境中开启 React Devtools // 如果需要在 h5 环境中开启 React Devtools
// 取消以下注释: // 取消以下注释:
...@@ -25,16 +27,41 @@ class App extends Component { ...@@ -25,16 +27,41 @@ class App extends Component {
* 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型 * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
*/ */
config: Config = { config: Config = {
pages: ['pages/index/index'], // pages: pages,
pages: ['pages/index/index', 'pages/login/index'],
window: { window: {
backgroundTextStyle: 'light', backgroundTextStyle: 'light',
navigationBarBackgroundColor: '#fff', navigationBarTextStyle: 'black',
navigationBarTitleText: 'WeChat', navigationBarTitleText: 'WeChat',
navigationBarTextStyle: 'black' navigationBarBackgroundColor: '#fff'
} }
} }
componentDidMount() {} constructor(props) {
super(props)
// debugger
// console.log({ pages })
// console.warn(Taro.getEnv())
console.log('object')
console.log('!token.isLogon()', token)
this.test()
// if (!token.isLogon()) {
// Taro.navigateTo({ url: 'pages/login/index' })
// }
}
async test() {
await new Promise((resolve, reject) => {
setTimeout(() => {
resolve()
}, 3000)
})
console.log('object')
}
componentDidMount() {
// api.user.request('')
}
componentDidShow() {} componentDidShow() {}
......
export const ADD = 'ADD' export const ADD = 'ADD'
export const MINUS = 'MINUS' export const MINUS = 'MINUS'
export const BASE_URL = 'http://xxxx.com'
export const FETCH_TIME_OUT = 5000
export const INTERFACE_REPEAT = '接口重复,请求已取消'
export const INDEX = 'pages/index/index'
export const LOGIN = 'pages/login/index'
export const pages = [INDEX, LOGIN]
// export default {
// pages: [INDEX, LOGIN]
// }
// pages: ['pages/login/index', 'pages/index/index'],
import Taro from '@tarojs/taro'
class Token {
private token
constructor() {
console.log('object111')
this.getStorageToken()
}
/** 检测用户是否登录 */
isLogon() {
return !!this.token
}
setToken(token: string) {
if (!token) return
this.token = token
// Taro.setStorage({ key: 'token', data: this.token })
// console.log({ res })
}
getToken() {
return this.token
}
getStorageToken() {
// Taro.getStorage({ key: 'token' }).then(({ data }) => {
// if (data) this.token = data
// })
}
}
export default new Token()
/** 连接参数 */
export function concatParam(data: any): string {
return Object.entries(data)
.map(([key, val]) => `${key}=${val}`)
.join('&')
}
// ex
import { ComponentClass } from 'react'
import Taro, { Component, Config } from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
// import { Text } from 'react-native'
import './login.less'
import { connect } from '@tarojs/redux'
type PageStateProps = {
counter: {
num: number
}
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
name: string
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps
interface Login {
props: IProps
state: PageState
}
@connect(({ counter }) => ({
counter
}))
class Login extends Component {
config: Config = {
navigationStyle: 'custom'
}
constructor(props) {
super(props)
this.state = {
name: '小红'
}
}
componentDidMount() {
// console.log(Taro.getEnv())
}
// componentWillReceiveProps(nextProps) {}
componentWillUnmount() {}
componentDidShow() {}
componentDidHide() {}
render() {
console.log(Taro.getEnv() === Taro.ENV_TYPE.RN)
return (
<View className="Login">
<Text>{this.state.name}</Text>
</View>
)
}
}
export default Login as ComponentClass<PageOwnProps, PageState>
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment