前端实现登录、登出、请求数据的一些思路整理
生活随笔
收集整理的這篇文章主要介紹了
前端实现登录、登出、请求数据的一些思路整理
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
前端實(shí)現(xiàn)登錄、登出、請(qǐng)求數(shù)據(jù)的一些思路整理(基于React、JWT技術(shù))
登錄、登出和數(shù)據(jù)請(qǐng)求是兩種不同的數(shù)據(jù)交互方式,是互相獨(dú)立的。
- 登錄、登出基于 JWT(JSON WEB TOKEN) 技術(shù),通過(guò)請(qǐng)求后臺(tái)的登錄接口,由服務(wù)器生成一個(gè) token 憑證返回給前臺(tái);前臺(tái)拿到 token 之后存儲(chǔ)到本地的 localStorage 里面,每次進(jìn)行數(shù)據(jù)請(qǐng)求的時(shí)候都帶上 token 傳給后臺(tái),由后臺(tái)決定根據(jù) token 返回不同的數(shù)據(jù)和狀態(tài)。
根據(jù)以上思路整理出前端代碼
-
① 登錄和登出
// 獲取當(dāng)前項(xiàng)目的請(qǐng)求前綴 const BaseAPI = process.env.REACT_APP_API; // 定義本地 token 的鍵 const localStorageKey = '__auth_provider_key__'; // 定義獲取本地 token 的方法 export const getToken = () => window.localStorage.getItem(localStorageKey); // 定義清除本地 token 的方法 export const removeToken = () => window.localStorage.removeItem(localStorageKey); // 定義登錄方法(核心) export const login = (data: { username: string, password: string }) => {return fetch(`${BaseAPI}/login`, {method: 'POST',headers: {'Content-Type': 'application/json'},body: JSON.stringify(data)}).then(async response => {if(response.ok){const result = response.json();window.localStorag.setItem(result.token || '');return result;}else{return Promise.reject(data);}}) } -
② 將 user 的數(shù)據(jù)和狀態(tài)共享為全局?jǐn)?shù)據(jù)
// 創(chuàng)建一個(gè) context 對(duì)象 interface User {id: string;name: string;token: string; }interface AuthForm {username: string;password: string; }const AuthContext = React.createContext<{user: User | null,loginMethod: (form: AuthForm) => Promise<void>,logoutMethod: () => Promise<void> } || undefined>(undefined); AuthContext.displayName = 'AuthContext';// 創(chuàng)建一個(gè) provider,將數(shù)據(jù)傳遞給消費(fèi)組件進(jìn)行共享 export const AuthProvider = () => {const [user, setUser] = useState<User | null>(null);const loginMethod = (form: AuthForm) => login(form).then(setUser);const logoutMethod = () => logout().then(setUser(null));return <AuthContext.Provider value={{user, loginMethod, logoutMethod}} />} // 由 app 組件作為消費(fèi)組件,全局共享 user 信息 <AuthProvider><App></App> </AuthProvider> // 額外封裝一個(gè) hooks,用于在消費(fèi)組件下面的任意地方獲取 AuthContext 的數(shù)據(jù) export const useAuth = () => {const context = React.useContext(AuthContext);if(!context){throw new Error("useAuth 必須在 AuthProvide 中使用")}else{return context;} } -
③ 封裝請(qǐng)求數(shù)據(jù)的 hooks
// 封裝請(qǐng)求方法 import qs from 'qs';interface Config extends RequestInit {data?: object;token?: string; }export const http = async (endPoint: string, {data, token, ...customConfig}: Config = {}) => {const config = {method: 'GET',headers: {Authorization: token ? `Bearer ${token}` : '','Content-Type': data ? 'application/json' : ''},...customConfig};if(config.method.toUpperCase() === 'GET'){endPoint += data ? `${qs.stringify(data)}`: '';}else{config.body = JSON.stringify(data || {});}return window.fetch(`${BaseAPI}/${endPoint}`, config).then(async response => {if(response.status == 401){await logout();return Promise.reject({message: '認(rèn)證過(guò)期,請(qǐng)重新登錄'})}const data = await response.json();if(response.ok){return data}else{return Promise.reject(data);}}) } // 根據(jù) user 的數(shù)據(jù),封裝數(shù)據(jù)請(qǐng)求 hooks export const useHttp = () => {const { user } = useAuth();return (...[endPoint, config]: Parameters<typeof http>) => http(endPoint, {...config, token: user?.token}); } // 使用 const httpRequest = useHttp(); httpRequest("lists").then(setLists);
總結(jié)
以上是生活随笔為你收集整理的前端实现登录、登出、请求数据的一些思路整理的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: python封装一个小游戏
- 下一篇: 前端京东案例总体思路