日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > HTML >内容正文

HTML

前端实现登录、登出、请求数据的一些思路整理

發(fā)布時(shí)間:2024/1/1 HTML 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 前端实现登录、登出、请求数据的一些思路整理 小編覺(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)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。