工程級(jí)?React?注冊(cè)登錄全棧級(jí)流程分析
創(chuàng)建前端項(xiàng)目
npm install create-react-app -g create-react-app my-app-client
create-react-app 是創(chuàng)建單頁面程序的腳手架
前端目錄結(jié)構(gòu)
創(chuàng)建好項(xiàng)目之后,刪掉 src 目錄下的文件,按照以下結(jié)構(gòu)創(chuàng)建目錄,根據(jù)具體項(xiàng)目情況進(jìn)行更改
引入 UI 組件庫
npm install antd -S
Ant Design 是企業(yè)級(jí)的 UI 設(shè)計(jì)語言和 React 組件庫
引入路由
npm install react-router-dom -S
使用路由進(jìn)行不同頁面間的切換
使用示例:
ReactDOM.render( <Provider store={store}> <HashRouter> <div className="container"> <Switch> {routes.map((route) => ( <Route key={route.path} {...route} /> ))} </Switch> </div> </HashRouter> </Provider>, document.getElementById("root") );
在 routes/index.js
中,引入需要的組件并導(dǎo)出路由配置對(duì)象
import Register from "../pages/register/Register"; import Login from "../pages/login/Login"; import Main from "../pages/main/Main"; export const routes = [ { path: "/register", component: Register, }, { path: "/login", component: Login, }, { path: "", component: Main, }, ];
引入 redux
npm install redux react-redux redux-thunk -S npm install redux-devtools-extension -D
注冊(cè)組件樣式
示例:
<Layout> <Header> <Logo /> </Header> <Content> <Input type="text"/> </Content> <Footer> <Button type="primary">注冊(cè)</Button> </Footer> </Layout>
在自己想要使用 antd 的組件中可使用 import {} from "antd"
即可引入組件樣式,任意使用
收集注冊(cè)數(shù)據(jù)
數(shù)據(jù)通過 state
儲(chǔ)存,通過綁定輸入框 onChange
事件更新數(shù)據(jù)
state = { username: "", password: "", againPassword: "", type: "", }; handleChange = (name, value) => { this.setState({ [name]: value, }); };
完成登錄組件
和注冊(cè)組件相同的方式完成登錄組件
注意:注冊(cè)和登錄組件中的路由跳轉(zhuǎn)使用 this.props.history
中的 replace()
或者 push()
方法實(shí)現(xiàn),區(qū)別是 replace 不能回退,push 可以回退
創(chuàng)建后端項(xiàng)目
express myapp-server -e
修改 bin/www
中的端口號(hào)為 4000,避免與前端的監(jiān)聽端口號(hào) 3000 沖突
使用 Postman 測(cè)試接口
自動(dòng)重啟后端工具
npm install nodemon -D
安裝之后將 package.json
中的 scripts.start
改為 nodemon ./bin/www
,啟動(dòng)之后每次修改代碼保存即可立即重啟
使用 mongodb
npm install mongoose blueimp-md5 -S
常見操作:save,find,findOne,findByIdAndUpdate,delete(remove 已經(jīng)過時(shí))
blueimp-md5 庫用來對(duì)密碼進(jìn)行 md5 加密,庫導(dǎo)出的是函數(shù),直接使用 blueimp-md5(password)即可返回加密結(jié)果
編寫數(shù)據(jù)庫操作模塊
使用操作 mongodb 數(shù)據(jù)庫的 mongoose 模塊向外暴露一個(gè)數(shù)據(jù)庫操作的類,這樣在路由中如果需要操作數(shù)據(jù)庫只需要引入類直接使用
const mongoose = require("mongoose"); mongoose.connect("mongodb://localhost:27017/school-chat"); const connection = mongoose.connection; connection.on("connected", () => { console.log("數(shù)據(jù)庫連接成功"); }); const userSchema = mongoose.Schema({ username: { type: String, required: true }, password: { type: String, required: true }, type: { type: String, required: true }, ... }); const UserModel = mongoose.model("user", userSchema); exports.UserModel = UserModel;
后端注冊(cè)路由
在 routes/index.js
中編寫后端所有的路由,路由中返回的對(duì)象儲(chǔ)存在前端 ajax 請(qǐng)求的響應(yīng)體中
注冊(cè)首先需要在數(shù)據(jù)庫中查找用戶是否存在,不存在才新建一條文檔
router.post("/register", (req, res) => { const { username, password, type } = req.body; UserModel.findOne({ username }, (err, user) => { if (user) { res.send({ code: 1, msg: `用戶“${username}”已存在` }); } else { const userModel = new UserModel({ username, password: md5(password), type }); userModel.save((err, user) => { res.cookie("userid", user._id, { maxAge: 1000 * 3600 * 24 * 7 }); res.send({ code: 0, data: { _id: user._id, username, type } }); }); } }); });
后端登錄路由
登錄首先需要在數(shù)據(jù)庫中查找用戶是否存在,存在才返回相應(yīng)的信息
router.post("/login", (req, res) => { const { username, password } = req.body; UserModel.findOne({ username, password: md5(password) }, filter, (err, user) => { if (user) { res.cookie("userid", user._id, { maxAge: 1000 * 3600 * 24 * 7 }); res.send({ code: 0, data: user }); } else { res.send({ code: 1, msg: "用戶名或密碼不正確" }); } }); });
前端請(qǐng)求函數(shù)封裝
npm install axios -S
主流請(qǐng)求分為 GET 請(qǐng)求和 POST 請(qǐng)求,GET 請(qǐng)求需要根據(jù) data 對(duì)象拼接出請(qǐng)求的 url
export default function ajax(url = "", data = {}, type = "GET") { if (type === "GET") { let queryStr = ""; for (let key in data) { queryStr += `${key}=${data[key]}&`; } if (queryStr !== "") { queryStr = queryStr.slice(0, -1); return axios.get(`${url}?${queryStr}`); } } else { return axios.post(url, data); } }
前端接口請(qǐng)求模塊
通過前面封裝的請(qǐng)求函數(shù),將項(xiàng)目中所有用到的請(qǐng)求都封裝成函數(shù)在 api/index.js
中
export const reqRegister = (user) => ajax("/register", user, "POST"); export const reqLogin = (username, password) => ajax("/login", { username, password }, "POST"); export const reqUpdate = (user) => ajax("/update", user, "POST"); ...
前端注冊(cè)的 redux
在 redux/actions.js
中編寫多個(gè) action creator:同步 action,異步 action
export const register = (user) => { const { username, password, againPassword, type } = user; if (!username) { return errorMsg("用戶名不能為空!"); } if (password !== againPassword) { return errorMsg("兩次密碼不一致!"); } return async (dispatch) => { const response = await reqRegister({ username, password, type }); const result = response.data; if (result.code === 0) { dispatch(authSuccess(result.data)); } else { dispatch(errorMsg(result.msg)); } }; };
異步 action 分發(fā)授權(quán)成功的同步 action(請(qǐng)求),在分發(fā)之前進(jìn)行前端驗(yàn)證,如果失敗就不分發(fā)同步 action,直接返回對(duì)應(yīng)的同步 action,因?yàn)檎?qǐng)求返回的值的類型的 Promise,所以需要使用 es7 中的 async 和 await 關(guān)鍵詞,authSuccess 和 errorMsg 同步 action 返回包含 action type 的對(duì)象
在 redux/reducers.js
中編寫所有的 reducer 函數(shù),然后使用 combineReducers 函數(shù)結(jié)合起來暴露出去
function user(state = initUser, action) { switch (action.type) { case AUTH_SUCCESS: return { ...action.data, redirectTo: "/" }; case ERROR_MSG: return { ...state, msg: action.data }; default: return state; } } export default combineReducers({ user, });
根據(jù)老的 user state 和指定的 action 返回新的 state
import { createStore, applyMiddleware } from "redux"; import thunk from "redux-thunk"; import { composeWithDevTools } from "redux-devtools-extension"; import reducers from "./reducers"; export default createStore(reducers, composeWithDevTools(applyMiddleware(thunk)));
最后,在 redux/store.js
中暴露編寫 redux 最核心部分,向外暴露 store 對(duì)象,代碼比較固定,在大部分項(xiàng)目中幾乎不變
完善登錄和注冊(cè)組件
登錄和注冊(cè)點(diǎn)擊發(fā)送請(qǐng)求的時(shí)候會(huì)出現(xiàn)瀏覽器跨域報(bào)錯(cuò),意思是 3000 端口向 4000 端口發(fā)送請(qǐng)求
一個(gè)簡(jiǎn)單的解決辦法是使用代理:在 package.json
中配置 "proxy": "http://localhost:4000"
,意思是配置一個(gè)在 3000 端口可以向 4000 端口轉(zhuǎn)發(fā)請(qǐng)求的代理,瀏覽器識(shí)別不出代理
將 redux 作用在在注冊(cè)和登錄組件上:
export default connect( (state) => ({ user: state.user, }), { register } )(Register);
其中 user 中的狀態(tài)可以通過 this.props.user
獲取,比如 this.props.user.msg
,然后就可以將 redux 中的狀態(tài)展現(xiàn)在組件中
注冊(cè)操作可使用 this.props.register(this.state)
進(jìn)行登錄
到此這篇關(guān)于工程級(jí) React 注冊(cè)登錄全棧級(jí)流程的文章就介紹到這了,更多相關(guān) React 注冊(cè)登錄內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React.js組件實(shí)現(xiàn)拖拽排序組件功能過程解析
這篇文章主要介紹了React.js組件實(shí)現(xiàn)拖拽排序組件功能過程解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04React?中使用?react-i18next?國(guó)際化的過程(react-i18next?的基本用法)
i18next?是一款強(qiáng)大的國(guó)際化框架,react-i18next?是基于?i18next?適用于?React?的框架,本文介紹了?react-i18next?的基本用法,如果更特殊的需求,文章開頭的官方地址可以找到答案2023-01-01詳解在React項(xiàng)目中如何集成和使用web worker
在復(fù)雜的React應(yīng)用中,某些計(jì)算密集型或耗時(shí)操作可能會(huì)阻塞主線程,導(dǎo)致用戶界面出現(xiàn)卡頓或響應(yīng)慢的現(xiàn)象,為了優(yōu)化用戶體驗(yàn),可以采用Web Worker來在后臺(tái)線程中執(zhí)行這些操作,本文將詳細(xì)介紹在React項(xiàng)目中如何集成和使用Web Worker來改善應(yīng)用性能,需要的朋友可以參考下2023-12-12React?+?Typescript領(lǐng)域初學(xué)者的常見問題和技巧(最新)
這篇文章主要介紹了React?+?Typescript領(lǐng)域初學(xué)者的常見問題和技巧,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06React前端渲染優(yōu)化--父組件導(dǎo)致子組件重復(fù)渲染的問題
本篇文章是針對(duì)父組件導(dǎo)致子組件重復(fù)渲染的優(yōu)化方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08React在定時(shí)器中無法獲取狀態(tài)最新值的問題
這篇文章主要介紹了React在定時(shí)器中無法獲取狀態(tài)最新值的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08關(guān)于antd tree和父子組件之間的傳值問題(react 總結(jié))
這篇文章主要介紹了關(guān)于antd tree 和父子組件之間的傳值問題,是小編給大家總結(jié)的一些react知識(shí)點(diǎn),本文通過一個(gè)項(xiàng)目需求實(shí)例代碼詳解給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-06-06react?app?rewrited替代品craco使用示例
這篇文章主要為大家介紹了react?app?rewrited替代品craco使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11