10.2 用 React + Redux + Node(Isomorphic JavaScript)开发食谱分享网站

优质
小牛编辑
125浏览
2023-12-01

前言

如果你是从一开始跟着我们踏出 React 旅程的读者真的恭喜你,也谢谢你一路跟着我们的学习脚步,对一个初学者来说这一段路并不容易。本章是扣除附录外我们最后一个正式章节的範例,也是规模最大的一个,在这个章节中我们要整合过去所学和添加一些知识开发一个可以登入会员并分享食谱的社群网站,Les’s GO!

需求规划

让使用者可以登入会员并分享食谱的社群网站

功能规划

  1. React Router / Redux / Immutable / Server Render / Async API
  2. 使用者登入/登出(JSON Web Token)
  3. CRUD 表单资料处理
  4. 资料库串接(ORM/MongoDB)

使用技术

  1. React
  2. Redux(redux-actions/redux-promise/redux-immutable)
  3. React Router
  4. ImmutableJS
  5. Node MongoDB ORM(Mongoose)
  6. JSON Web Token
  7. React Bootstrap
  8. Axios(Promise)
  9. Webpack
  10. UUID

专案成果截图

用 React + Redux + Node(Isomorphic)开发一个食谱分享网站

用 React + Redux + Node(Isomorphic)开发一个食谱分享网站

用 React + Redux + Node(Isomorphic)开发一个食谱分享网站

用 React + Redux + Node(Isomorphic)开发一个食谱分享网站

环境安装与设定

  1. 安装 Node 和 NPM

  2. 安装所需套件

  1. $ npm install --save react react-dom redux react-redux react-router immutable redux-immutable redux-actions redux-promise bcrypt body-parser cookie-parser debug express immutable jsonwebtoken mongoose morgan passport passport-local react-router-bootstrap axios serve-favicon validator uuid
  1. $ npm install --save-dev babel-core babel-eslint babel-loader babel-preset-es2015 babel-preset-react babel-preset-stage-1 eslint eslint-config-airbnb eslint-loader eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react html-webpack-plugin webpack webpack-dev-server redux-logger

接下来我们先设定一下开发文档。

  1. 设定 Babel 的设定档: .babelrc

    1. {
    2. "presets": [
    3. "es2015",
    4. "react",
    5. ],
    6. "plugins": []
    7. }
  2. 设定 ESLint 的设定档和规则: .eslintrc

    1. {
    2. "extends": "airbnb",
    3. "rules": {
    4. "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
    5. },
    6. "env" :{
    7. "browser": true,
    8. }
    9. }
  3. 设定 Webpack 设定档: webpack.config.js

    1. import webpack from 'webpack';
    2. module.exports = {
    3. entry: [
    4. './src/client/index.js',
    5. ],
    6. output: {
    7. path: `${__dirname}/dist`,
    8. filename: 'bundle.js',
    9. publicPath: '/static/'
    10. },
    11. module: {
    12. preLoaders: [
    13. {
    14. test: /\.jsx$|\.js$/,
    15. loader: 'eslint-loader',
    16. include: `${__dirname}/app`,
    17. exclude: /bundle\.js$/,
    18. },
    19. ],
    20. // 使用 Hot Module Replacement 外挂
    21. plugins: [
    22. new webpack.optimize.OccurrenceOrderPlugin(),
    23. new webpack.HotModuleReplacementPlugin()
    24. ],
    25. loaders: [{
    26. test: /\.js$/,
    27. exclude: /node_modules/,
    28. loader: 'babel-loader',
    29. query: {
    30. presets: ['es2015', 'react'],
    31. },
    32. }],
    33. },
    34. };
  4. 设定 src/server/config/index.js

  1. export default ({
  2. "secret": "ilovecooking",
  3. "database": "mongodb://localhost/open_cook"
  4. });

太好了!这样我们就完成了开发环境的设定可以开始动手实作我们的食谱分享社群应用程式了!

同时我们也初步设计我们资料夹结构,主要我们将资料夹分为 clientcommonserver

动手实作

首先我们先进行 src/client/index.js 的设计:

  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import { Provider } from 'react-redux';
  4. import { browserHistory, Router } from 'react-router';
  5. import { fromJS } from 'immutable';
  6. // 我们的 routing 放置在 common 资料夹中的 routes
  7. import routes from '../common/routes';
  8. import configureStore from '../common/store/configureStore';
  9. import { checkAuth } from '../common/actions';
  10. // 将 server side 传过来的 initialState 给 rehydration(覆水)
  11. const initialState = window.__PRELOADED_STATE__;
  12. // 将 initialState 传给 configureStore 函数创建出 store 并传给 Provider
  13. const store = configureStore(fromJS(initialState));
  14. ReactDOM.render(
  15. <Provider store={store}>
  16. <Router history={browserHistory} routes={routes} />
  17. </Provider>,
  18. document.getElementById('app')
  19. );

由于 Node 端要到新版对于 ES6 支援较好,所以先用 babel-registersrc/server/index.js 去即时转译 server.js,但不建议在 production 环境使用。

  1. // use babel-register to precompile ES6
  2. require('babel-register');
  3. require('./server');
  1. // 引入 Express、mongoose(MongoDB ORM)以及相关 server 上使用的套件
  2. /* Server Packages */
  3. import Express from 'express';
  4. import bodyParser from 'body-parser';
  5. import cookieParser from 'cookie-parser';
  6. import morgan from 'morgan';
  7. import mongoose from 'mongoose';
  8. import config from './config';
  9. // 引入后端 model 透过 model 和资料库互动
  10. import User from './models/user';
  11. import Recipe from './models/recipe';
  12. // 引入 webpackDevMiddleware 当做前端 server middleware
  13. /* Client Packages */
  14. import webpack from 'webpack';
  15. import React from 'react';
  16. import webpackDevMiddleware from 'webpack-dev-middleware';
  17. import webpackHotMiddleware from 'webpack-hot-middleware';
  18. import { RouterContext, match } from 'react-router';
  19. import { renderToString } from 'react-dom/server';
  20. import { Provider } from 'react-redux';
  21. import Immutable, { fromJS } from 'immutable';
  22. /* Common Packages */
  23. import webpackConfig from '../../webpack.config';
  24. import routes from '../common/routes';
  25. import configureStore from '../common/store/configureStore';
  26. import fetchComponentData from '../common/utils/fetchComponentData';
  27. import apiRoutes from './controllers/api.js';
  28. /* config */
  29. // 初始化 Express server
  30. const app = new Express();
  31. const port = process.env.PORT || 3000;
  32. // 连接到资料库,相关设定档案放在 config.database
  33. mongoose.connect(config.database); // connect to database
  34. app.set('env', 'production');
  35. // 设定静态档案位置
  36. app.use('/static', Express.static(__dirname + '/public'));
  37. app.use(cookieParser());
  38. // use body parser so we can get info from POST and/or URL parameters
  39. app.use(bodyParser.urlencoded({ extended: false })); // only can deal with key/value
  40. app.use(bodyParser.json());
  41. // use morgan to log requests to the console
  42. app.use(morgan('dev'));
  43. // 负责每次接受到 request 的处理函数,判断该如何处理和取得 initialState 整理后结合伺服器渲染页面传往前端
  44. const handleRender = (req, res) => {
  45. // Query our mock API asynchronously
  46. match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
  47. if (error) {
  48. res.status(500).send(error.message);
  49. } else if (redirectLocation) {
  50. res.redirect(302, redirectLocation.pathname + redirectLocation.search);
  51. } else if (renderProps == null) {
  52. res.status(404).send('Not found');
  53. }
  54. fetchComponentData(req.cookies.token).then((response) => {
  55. let isAuthorized = false;
  56. if (response[1].data.success === true) {
  57. isAuthorized = true;
  58. } else {
  59. isAuthorized = false;
  60. }
  61. const initialState = fromJS({
  62. recipe: {
  63. recipes: response[0].data,
  64. recipe: {
  65. id: '',
  66. name: '',
  67. description: '',
  68. imagePath: '',
  69. }
  70. },
  71. user: {
  72. isAuthorized: isAuthorized,
  73. isEdit: false,
  74. }
  75. });
  76. // server side 渲染页面
  77. // Create a new Redux store instance
  78. const store = configureStore(initialState);
  79. const initView = renderToString(
  80. <Provider store={store}>
  81. <RouterContext {...renderProps} />
  82. </Provider>
  83. );
  84. let state = store.getState();
  85. let page = renderFullPage(initView, state);
  86. return res.status(200).send(page);
  87. })
  88. .catch(err => res.end(err.message));
  89. })
  90. }
  91. // 基础页面 HTML 设计
  92. const renderFullPage = (html, preloadedState) => (`
  93. <!doctype html>
  94. <html>
  95. <head>
  96. <title>OpenCook 分享料理的美好时光</title>
  97. <!-- Latest compiled and minified CSS -->
  98. <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
  99. <!-- Optional theme -->
  100. <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css">
  101. <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.7/journal/bootstrap.min.css">
  102. <body>
  103. <div id="app">${html}</div>
  104. <script>
  105. window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState).replace(/</g, '\\x3c')}
  106. </script>
  107. <script src="/static/bundle.js"></script>
  108. </body>
  109. </html>`
  110. );
  111. // 设定 hot reload middleware
  112. const compiler = webpack(webpackConfig);
  113. app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath }));
  114. app.use(webpackHotMiddleware(compiler));
  115. // 设计 API prefix,并使用 controller 中的 apiRoutes 进行处理
  116. app.use('/api', apiRoutes);
  117. // 使用伺服器端 handleRender
  118. app.use(handleRender);
  119. app.listen(port, (error) => {
  120. if (error) {
  121. console.error(error)
  122. } else {
  123. console.info(`==> ? Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`)
  124. }
  125. });

由于 Node 端要到新版对于 ES6 支援较好,所以先用 babel-registersrc/server/index.js 去即时转译 server.js,但目前不建议在 production 环境使用。

  1. // use babel-register to precompile ES6 syntax
  2. require('babel-register');
  3. require('./server');

现在我们来设计一下我们资料库的 Schema,在这边我们使用 MongoDB 的 ORM Mongoose,可以方便我们使用物件方式进行资料库的操作:

  1. // 引入 mongoose 和 Schema
  2. import mongoose, { Schema } from 'mongoose';
  3. // 使用 mongoose.model 建立新的资料表,并将 Schema 传入
  4. // 这边我们设计了食谱分享的一些基本要素,包括名称、描述、照片位置等
  5. export default mongoose.model('Recipe', new Schema({
  6. id: String,
  7. name: String,
  8. description: String,
  9. imagePath: String,
  10. steps: Array,
  11. updatedAt: Date,
  12. }));
  1. // 引入 mongoose 和 Schema
  2. import mongoose, { Schema } from 'mongoose';
  3. // 使用 mongoose.model 建立新的资料表,并将 Schema 传入
  4. // 这边我们设计了使用者的一些基本要素,包括名称、描述、照片位置等
  5. export default mongoose.model('User', new Schema({
  6. id: Number,
  7. username: String,
  8. email: String,
  9. password: String,
  10. admin: Boolean
  11. }));

为了方便维护,我们把 API 的部份统一在 src/server/controllers/api.js 进行管理,这部份会涉及比较多 Node 和 mongoose 的操作,若读者尚不熟悉可以参考 mongoose 官网

  1. import Express from 'express';
  2. // 引入 jsonwebtoken 套件
  3. import jwt from 'jsonwebtoken';
  4. // 引入 User、Recipe Model 方便进行资料库操作
  5. import User from '../models/user';
  6. import Recipe from '../models/recipe';
  7. import config from '../config';
  8. // API Route
  9. const app = new Express();
  10. const apiRoutes = Express.Router();
  11. // 设定 JSON Web Token 的 secret variable
  12. app.set('superSecret', config.secret); // secret variable
  13. // 使用者登入 API ,依据使用 email 和 密码去验证,若成功则回传一个认证 token(时效24小时)我们把它存在 cookie 中,方便前后端存取。这边我们先不考虑太多资讯安全的议题
  14. apiRoutes.post('/login', function(req, res) {
  15. // find the user
  16. User.findOne({
  17. email: req.body.email
  18. }, (err, user) => {
  19. if (err) throw err;
  20. if (!user) {
  21. res.json({ success: false, message: 'Authentication failed. User not found.' });
  22. } else if (user) {
  23. // check if password matches
  24. if (user.password != req.body.password) {
  25. res.json({ success: false, message: 'Authentication failed. Wrong password.' });
  26. } else {
  27. // if user is found and password is right
  28. // create a token
  29. const token = jwt.sign({ email: user.email }, app.get('superSecret'), {
  30. expiresIn: 60 * 60 * 24 // expires in 24 hours
  31. });
  32. // return the information including token as JSON
  33. // 若登入成功回传一个 json 讯息
  34. res.json({
  35. success: true,
  36. message: 'Enjoy your token!',
  37. token: token,
  38. userId: user._id
  39. });
  40. }
  41. }
  42. });
  43. });
  44. // 初始化 api,一开始资料库尚未建立任何使用者,我们需要在浏览器输入 `http://localhost:3000/api/setup`,进行资料库初始化。这个动作将新增一个使用者、一份食谱,若是成功新增将回传一个 success 讯息
  45. apiRoutes.get('/setup', (req, res) => {
  46. // create a sample user
  47. const sampleUser = new User({
  48. username: 'mark',
  49. email: 'mark@demo.com',
  50. password: '123456',
  51. admin: true
  52. });
  53. const sampleRecipe = new Recipe({
  54. id: '110ec58a-a0f2-4ac4-8393-c866d813b8d1',
  55. name: '番茄炒蛋',
  56. description: '番茄炒蛋,一道非常经典的家常菜料理。虽然看似普通,但每个家庭都有属于自己家里的不同味道',
  57. imagePath: 'https://c1.staticflickr.com/6/5011/5510599760_6668df5a8a_z.jpg',
  58. steps: ['放入番茄', '打个蛋', '放入少许盐巴', '用心快炒'],
  59. updatedAt: new Date()
  60. });
  61. // save the sample user
  62. sampleUser.save((err) => {
  63. if (err) throw err;
  64. sampleRecipe.save((err) => {
  65. if (err) throw err;
  66. console.log('User saved successfully');
  67. res.json({ success: true });
  68. })
  69. });
  70. });
  71. // 回传所有 recipes
  72. apiRoutes.get('/recipes', (req, res) => {
  73. Recipe.find({}, (err, recipes) => {
  74. res.status(200).json(recipes);
  75. })
  76. });
  77. // route middleware to verify a token
  78. // 接下来的 api 将进行控管,也就是说必须在网址请求中夹带认证 token 才能完成请求
  79. apiRoutes.use((req, res, next) => {
  80. // check header or url parameters or post parameters for token
  81. // 确认标头、网址或 post 参数是否含有 token,本範例因为简便使用网址 query 参数
  82. var token = req.body.token || req.query.token || req.headers['x-access-token'];
  83. // decode token
  84. if (token) {
  85. // verifies secret and checks exp
  86. jwt.verify(token, app.get('superSecret'), (err, decoded) => {
  87. if (err) {
  88. return res.json({ success: false, message: 'Failed to authenticate token.' });
  89. } else {
  90. // if everything is good, save to request for use in other routes
  91. req.decoded = decoded;
  92. next();
  93. }
  94. });
  95. } else {
  96. // if there is no token
  97. // return an error
  98. return res.status(403).send({
  99. success: false,
  100. message: 'No token provided.'
  101. });
  102. }
  103. });
  104. // 确认认证是否成功
  105. apiRoutes.get('/authenticate', (req, res) => {
  106. res.json({
  107. success: true,
  108. message: 'Enjoy your token!',
  109. });
  110. });
  111. // create recipe 新增食谱
  112. apiRoutes.post('/recipes', (req, res) => {
  113. const newRecipe = new Recipe({
  114. name: req.body.name,
  115. description: req.body.description,
  116. imagePath: req.body.imagePath,
  117. steps: ['放入番茄', '打个蛋', '放入少许盐巴', '用心快炒'],
  118. updatedAt: new Date()
  119. });
  120. newRecipe.save((err) => {
  121. if (err) throw err;
  122. console.log('User saved successfully');
  123. res.json({ success: true });
  124. });
  125. });
  126. // update recipe 根据 _id(mongodb 的 id)更新食谱
  127. apiRoutes.put('/recipes/:id', (req, res) => {
  128. Recipe.update({ _id: req.params.id }, {
  129. name: req.body.name,
  130. description: req.body.description,
  131. imagePath: req.body.imagePath,
  132. steps: ['放入番茄', '打个蛋', '放入少许盐巴', '用心快炒'],
  133. updatedAt: new Date()
  134. } ,(err) => {
  135. if (err) throw err;
  136. console.log('User updated successfully');
  137. res.json({ success: true });
  138. });
  139. });
  140. // remove recipe 根据 _id 删除食谱,若成功回传成功讯息
  141. apiRoutes.delete('/recipes/:id', (req, res) => {
  142. Recipe.remove({ _id: req.params.id }, (err, recipe) => {
  143. if (err) throw err;
  144. console.log('remove saved successfully');
  145. res.json({ success: true });
  146. });
  147. });
  148. export default apiRoutes;

设定整个 App 的 routing,我们主要页面有 HomePageContainerLoginPageContainerSharePageContainer,值得注意的是我们这边使用 Higher Order Components (Higher Order Components 为一个函数, 接收一个 Component 后在 Class Component 的 render 中 return 回传入的 components)方式去确认使用者是否有登入,若有没登入则不能进入分享食谱页面,反之若已登入也不会再进到登入页面:

  1. import React from 'react';
  2. import { Route, IndexRoute } from 'react-router';
  3. import Main from '../components/Main';
  4. import CheckAuth from '../components/CheckAuth';
  5. import HomePageContainer from '../containers/HomePageContainer';
  6. import LoginPageContainer from '../containers/LoginPageContainer';
  7. import SharePageContainer from '../containers/SharePageContainer';
  8. export default (
  9. <Route path='/' component={Main}>
  10. <IndexRoute component={HomePageContainer} />
  11. <Route path="/login" component={CheckAuth(LoginPageContainer, 'guest')}/>
  12. <Route path="/share" component={CheckAuth(SharePageContainer, 'auth')}/>
  13. </Route>
  14. );

设定行为常数(src/constants/actionTypes.js):

  1. export const AUTH_START = "AUTH_START";
  2. export const AUTH_COMPLETE = "AUTH_COMPLETE";
  3. export const AUTH_ERROR = "AUTH_ERROR";
  4. export const START_LOGOUT = "START_LOGOUT";
  5. export const CHECK_AUTH = "CHECK_AUTH";
  6. export const SET_USER = "SET_USER";
  7. export const SHOW_SPINNER = "SHOW_SPINNER";
  8. export const HIDE_SPINNER = "HIDE_SPINNER";
  9. export const SET_UI = "SET_UI";
  10. export const GET_RECIPES = 'GET_RECIPES';
  11. export const SET_RECIPE = 'SET_RECIPE';
  12. export const ADD_RECIPE = 'ADD_RECIPE';
  13. export const UPDATE_RECIPE = 'UPDATE_RECIPE';
  14. export const DELETE_RECIPE = 'DELETE_RECIPE';

设定 src/actions/recipeActions.js,我们这边使用 redux-promise,可以很容易使用非同步的行为 WebAPI:

  1. import { createAction } from 'redux-actions';
  2. import WebAPI from '../utils/WebAPI';
  3. import {
  4. GET_RECIPES,
  5. ADD_RECIPE,
  6. UPDATE_RECIPE,
  7. DELETE_RECIPE,
  8. SET_RECIPE,
  9. } from '../constants/actionTypes';
  10. export const getRecipes = createAction('GET_RECIPES', WebAPI.getRecipes);
  11. export const addRecipe = createAction('ADD_RECIPE', WebAPI.addRecipe);
  12. export const updateRecipe = createAction('UPDATE_RECIPE', WebAPI.updateRecipe);
  13. export const deleteRecipe = createAction('DELETE_RECIPE', WebAPI.deleteRecipe);
  14. export const setRecipe = createAction('SET_RECIPE');

设定 src/actions/uiActions.js

  1. import { createAction } from 'redux-actions';
  2. import WebAPI from '../utils/WebAPI';
  3. import {
  4. SHOW_SPINNER,
  5. HIDE_SPINNER,
  6. SET_UI,
  7. } from '../constants/actionTypes';
  8. export const showSpinner = createAction('SHOW_SPINNER');
  9. export const hideSpinner = createAction('HIDE_SPINNER');
  10. export const setUi = createAction('SET_UI');

设定 src/actions/userActions.js,处理使用者登入登出等行为:

  1. import { createAction } from 'redux-actions';
  2. import WebAPI from '../utils/WebAPI';
  3. import {
  4. AUTH_START,
  5. AUTH_COMPLETE,
  6. AUTH_ERROR,
  7. START_LOGOUT,
  8. CHECK_AUTH,
  9. SET_USER
  10. } from '../constants/actionTypes';
  11. export const authStart = createAction('AUTH_START', WebAPI.login);
  12. export const authComplete = createAction('AUTH_COMPLETE');
  13. export const authError = createAction('AUTH_ERROR');
  14. export const startLogout = createAction('START_LOGOUT', WebAPI.logout);
  15. export const checkAuth = createAction('CHECK_AUTH');
  16. export const setUser = createAction('SET_USER');

scr/actions/index.js 输出 actions:

  1. export * from './userActions';
  2. export * from './recipeActions';
  3. export * from './uiActions';

scr/common/utils/fetchComponentData.js 设定 server side 初始 fetchComponentData:

  1. // 这边使用 axios 方便进行 promises base request
  2. import axios from 'axios';
  3. // 记得附加上我们存在 cookies 的 token
  4. export default function fetchComponentData(token = 'token') {
  5. const promises = [axios.get('http://localhost:3000/api/recipes'), axios.get('http://localhost:3000/api/authenticate?token=' + token)];
  6. return Promise.all(promises);
  7. }

scr/common/utils/WebAPI.js 所有前端 API 的处理:

  1. import axios from 'axios';
  2. import { browserHistory } from 'react-router';
  3. // 引入 uuid 当做食谱 id
  4. import uuid from 'uuid';
  5. import {
  6. authComplete,
  7. authError,
  8. hideSpinner,
  9. completeLogout,
  10. } from '../actions';
  11. // getCookie 函数传入 key 回传 value
  12. function getCookie(keyName) {
  13. var name = keyName + '=';
  14. const cookies = document.cookie.split(';');
  15. for(let i = 0; i < cookies.length; i++) {
  16. let cookie = cookies[i];
  17. while (cookie.charAt(0)==' ') {
  18. cookie = cookie.substring(1);
  19. }
  20. if (cookie.indexOf(name) == 0) {
  21. return cookie.substring(name.length, cookie.length);
  22. }
  23. }
  24. return "";
  25. }
  26. export default {
  27. // 呼叫后端登入 api
  28. login: (dispatch, email, password) => {
  29. axios.post('/api/login', {
  30. email: email,
  31. password: password
  32. })
  33. .then((response) => {
  34. if(response.data.success === false) {
  35. dispatch(authError());
  36. dispatch(hideSpinner());
  37. alert('发生错误,请再试一次!');
  38. window.location.reload();
  39. } else {
  40. if (!document.cookie.token) {
  41. let d = new Date();
  42. d.setTime(d.getTime() + (24 * 60 * 60 * 1000));
  43. const expires = 'expires=' + d.toUTCString();
  44. document.cookie = 'token=' + response.data.token + '; ' + expires;
  45. dispatch(authComplete());
  46. dispatch(hideSpinner());
  47. browserHistory.push('/');
  48. }
  49. }
  50. })
  51. .catch(function (error) {
  52. dispatch(authError());
  53. });
  54. },
  55. // 呼叫后端登出 api
  56. logout: (dispatch) => {
  57. document.cookie = 'token=; ' + 'expires=Thu, 01 Jan 1970 00:00:01 GMT;';
  58. dispatch(hideSpinner());
  59. browserHistory.push('/');
  60. },
  61. // 确认使用者是否登入
  62. checkAuth: (dispatch, token) => {
  63. axios.post('/api/authenticate', {
  64. token: token,
  65. })
  66. .then((response) => {
  67. if(response.data.success === false) {
  68. dispatch(authError());
  69. } else {
  70. dispatch(authComplete());
  71. }
  72. })
  73. .catch(function (error) {
  74. dispatch(authError());
  75. });
  76. },
  77. // 取得目前所有食谱
  78. getRecipes: () => {
  79. axios.get('/api/recipes')
  80. .then((response) => {
  81. })
  82. .catch((error) => {
  83. });
  84. },
  85. // 呼叫新增食谱 api,记得附加上我们存在 cookies 的 token
  86. addRecipe: (dispatch, name, description, imagePath) => {
  87. const id = uuid.v4();
  88. axios.post('/api/recipes?token=' + getCookie('token'), {
  89. id: id,
  90. name: name,
  91. description: description,
  92. imagePath: imagePath,
  93. })
  94. .then((response) => {
  95. if(response.data.success === false) {
  96. dispatch(hideSpinner());
  97. alert('发生错误,请再试一次!');
  98. browserHistory.push('/share');
  99. } else {
  100. dispatch(hideSpinner());
  101. window.location.reload();
  102. browserHistory.push('/');
  103. }
  104. })
  105. .catch(function (error) {
  106. });
  107. },
  108. // 呼叫更新食谱 api,记得附加上我们存在 cookies 的 token
  109. updateRecipe: (dispatch, recipeId, name, description, imagePath) => {
  110. axios.put('/api/recipes/' + recipeId + '?token=' + getCookie('token'), {
  111. id: recipeId,
  112. name: name,
  113. description: description,
  114. imagePath: imagePath,
  115. })
  116. .then((response) => {
  117. if(response.data.success === false) {
  118. dispatch(hideSpinner());
  119. dispatch(setRecipe({ key: 'recipeId', value: '' }));
  120. dispatch(setUi({ key: 'isEdit', value: false }));
  121. alert('发生错误,请再试一次!');
  122. browserHistory.push('/share');
  123. } else {
  124. dispatch(hideSpinner());
  125. window.location.reload();
  126. browserHistory.push('/');
  127. }
  128. })
  129. .catch(function (error) {
  130. });
  131. },
  132. // 呼叫删除食谱 api,记得附加上我们存在 cookies 的 token
  133. deleteRecipe: (dispatch, recipeId) => {
  134. axios.delete('/api/recipes/' + recipeId + '?token=' + getCookie('token'))
  135. .then((response) => {
  136. if(response.data.success === false) {
  137. dispatch(hideSpinner());
  138. alert('发生错误,请再试一次!');
  139. browserHistory.push('/');
  140. } else {
  141. dispatch(hideSpinner());
  142. window.location.reload();
  143. browserHistory.push('/');
  144. }
  145. })
  146. .catch(function (error) {
  147. });
  148. }
  149. };

接下来设定我们的 reducers,以下是 src/common/reducers/data/recipeReducers.jsGET_RECIPES 负责将后端 API 取得的所有食谱存放在 recipes 中:

  1. import { handleActions } from 'redux-actions';
  2. import { RecipeState } from '../../constants/models';
  3. import {
  4. GET_RECIPES,
  5. SET_RECIPE,
  6. } from '../../constants/actionTypes';
  7. const recipeReducers = handleActions({
  8. GET_RECIPES: (state, { payload }) => (
  9. state.set(
  10. 'recipes',
  11. payload.recipes
  12. )
  13. ),
  14. SET_RECIPE: (state, { payload }) => (
  15. state.setIn(payload.keyPath, payload.value)
  16. ),
  17. }, RecipeState);
  18. export default recipeReducers;

以下是 src/common/reducers/data/userReducers.js,负责确认登入相关处理事项。注意的是由于登入是非同步执行,所以会有几个阶段的行为要做处理:

  1. import { handleActions } from 'redux-actions';
  2. import { UserState } from '../../constants/models';
  3. import {
  4. AUTH_START,
  5. AUTH_COMPLETE,
  6. AUTH_ERROR,
  7. LOGOUT_START,
  8. SET_USER,
  9. } from '../../constants/actionTypes';
  10. const userReducers = handleActions({
  11. AUTH_START: (state) => (
  12. state.merge({
  13. isAuthorized: false,
  14. })
  15. ),
  16. AUTH_COMPLETE: (state) => (
  17. state.merge({
  18. email: '',
  19. password: '',
  20. isAuthorized: true,
  21. })
  22. ),
  23. AUTH_ERROR: (state) => (
  24. state.merge({
  25. username: '',
  26. email: '',
  27. password: '',
  28. isAuthorized: false,
  29. })
  30. ),
  31. START_LOGOUT: (state) => (
  32. state.merge({
  33. isAuthorized: false,
  34. })
  35. ),
  36. CHECK_AUTH: (state) => (
  37. state.set('isAuthorized', true)
  38. ),
  39. SET_USER: (state, { payload }) => (
  40. state.set(payload.key, payload.value)
  41. ),
  42. }, UserState);
  43. export default userReducers;

以下是 src/common/reducers/ui/uiReducers.js,负责确认 UI State 相关处理:

  1. import { handleActions } from 'redux-actions';
  2. import { UiState } from '../../constants/models';
  3. import {
  4. SHOW_SPINNER,
  5. HIDE_SPINNER,
  6. SET_UI,
  7. } from '../../constants/actionTypes';
  8. const uiReducers = handleActions({
  9. SHOW_SPINNER: (state) => (
  10. state.set(
  11. 'spinnerVisible',
  12. true
  13. )
  14. ),
  15. HIDE_SPINNER: (state) => (
  16. state.set(
  17. 'spinnerVisible',
  18. false
  19. )
  20. ),
  21. SET_UI: (state, { payload }) => (
  22. state.set(payload.key, payload.value)
  23. ),
  24. }, UiState);
  25. export default uiReducers;

最后把所有 recipes 在 src/common/reducers/index.js 使用 combineReducers 整合在一起,注意的是我们整个 App 的资料流要维持 immutable:

  1. import { combineReducers } from 'redux-immutable';
  2. import ui from './ui/uiReducers';
  3. import recipe from './data/recipeReducers';
  4. import user from './data/userReducers';
  5. // import routes from './routes';
  6. const rootReducer = combineReducers({
  7. ui,
  8. recipe,
  9. user,
  10. });
  11. export default rootReducer;

以下是 src/common/store/configureStore.js 处理 store 的建立,这次我们使用了 promiseMiddleware 的 middleware:

  1. import { createStore, applyMiddleware } from 'redux';
  2. import promiseMiddleware from 'redux-promise';
  3. import createLogger from 'redux-logger';
  4. import Immutable from 'immutable';
  5. import rootReducer from '../reducers';
  6. const initialState = Immutable.Map();
  7. export default function configureStore(preloadedState = initialState) {
  8. const store = createStore(
  9. rootReducer,
  10. preloadedState,
  11. applyMiddleware(createLogger({ stateTransformer: state => state.toJS() }, promiseMiddleware))
  12. );
  13. return store;
  14. }

经过一连串努力,我们来到了 View 的布建。在这个 App 中我们主要会由一个 AppBar 负责所有页面的导览,也就是每个页面都会有 AppBar 常驻在上面,然而上面的内容则会依 UI State 中的 isAuthorized 而有所不同。最后要留意的是我们使用了 React Bootstrapt 来建立 React Component。

  1. import React from 'react';
  2. import { LinkContainer } from 'react-router-bootstrap';
  3. import { Link } from 'react-router';
  4. import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
  5. const AppBar = ({
  6. isAuthorized,
  7. onToShare,
  8. onLogout,
  9. }) => (
  10. <Navbar>
  11. <Navbar.Header>
  12. <Navbar.Brand>
  13. <Link to="/">OpenCook</Link>
  14. </Navbar.Brand>
  15. <Navbar.Toggle />
  16. </Navbar.Header>
  17. <Navbar.Collapse>
  18. {
  19. isAuthorized === false ?
  20. (
  21. <Nav pullRight>
  22. <LinkContainer to={{ pathname: '/login' }}><NavItem eventKey={2} href="#">登入</NavItem></LinkContainer>
  23. </Nav>
  24. ) :
  25. (
  26. <Nav pullRight>
  27. <NavItem eventKey={1} onClick={onToShare}>分享食谱</NavItem>
  28. <NavItem eventKey={2} onClick={onLogout} href="#">登出</NavItem>
  29. </Nav>
  30. )
  31. }
  32. </Navbar.Collapse>
  33. </Navbar>
  34. );
  35. export default AppBar;

以下是 src/common/containers/AppBarContainer/AppBarContainer.js

  1. import React from 'react';
  2. import { connect } from 'react-redux';
  3. import AppBar from '../../components/AppBar';
  4. import { browserHistory } from 'react-router';
  5. import {
  6. startLogout,
  7. setRecipe,
  8. setUi,
  9. } from '../../actions';
  10. export default connect(
  11. (state) => ({
  12. isAuthorized: state.getIn(['user', 'isAuthorized']),
  13. }),
  14. (dispatch) => ({
  15. onToShare: () => {
  16. dispatch(setRecipe({ key: 'recipeId', value: '' }));
  17. dispatch(setUi({ key: 'isEdit', value: false }));
  18. window.location.reload();
  19. browserHistory.push('/share');
  20. },
  21. onLogout: () => (
  22. dispatch(startLogout(dispatch))
  23. ),
  24. })
  25. )(AppBar);

以下是 src/components/Main/Main.js,透过 route 机制让 AppBarContainer 可以成为整个 App 母模版:

  1. import React from 'react';
  2. import AppBarContainer from '../../containers/AppBarContainer';
  3. const Main = (props) => (
  4. <div>
  5. <AppBarContainer />
  6. <div>
  7. {props.children}
  8. </div>
  9. </div>
  10. );
  11. export default Main;

checkAuth 这个 Component 中,我们使用到了 Higher Order Components 的观念。Higher Order Components 为一个函数, 接收一个 Component 后在 Class Component 的 render 中 return 回传入的 components 方式去确认使用者是否有登入,若有没登入则不能进入分享食谱页面,反之若已登入也不会再进到登入页面:

  1. import React from 'react';
  2. import { connect } from 'react-redux';
  3. import { withRouter } from 'react-router';
  4. // High Order Component
  5. export default function requireAuthentication(Component, type) {
  6. class AuthenticatedComponent extends React.Component {
  7. componentWillMount() {
  8. this.checkAuth();
  9. }
  10. componentWillReceiveProps(nextProps) {
  11. this.checkAuth();
  12. }
  13. checkAuth() {
  14. if(type === 'auth') {
  15. if (!this.props.isAuthorized) {
  16. this.props.router.push('/');
  17. }
  18. } else {
  19. if (this.props.isAuthorized) {
  20. this.props.router.push('/');
  21. }
  22. }
  23. }
  24. render() {
  25. return (
  26. <div>
  27. {
  28. (type === 'auth') ?
  29. this.props.isAuthorized === true ? <Component {...this.props } /> : null
  30. : this.props.isAuthorized === false ? <Component {...this.props } /> : null
  31. }
  32. </div>
  33. )
  34. }
  35. };
  36. const mapStateToProps = (state) => ({
  37. isAuthorized: state.getIn(['user', 'isAuthorized']),
  38. });
  39. return connect(mapStateToProps)(withRouter(AuthenticatedComponent));
  40. }

我们将每个食谱呈现设计成 RecipeBox,以下是在 src/common/components/HomePage/HomePage.js 使用 map 方法去迭代我们的食谱:

  1. import React from 'react';
  2. import RecipeBoxContainer from '../../containers/RecipeBoxContainer';
  3. const HomePage = ({
  4. recipes
  5. }) => (
  6. <div>
  7. {
  8. recipes.map((recipe, index) => (
  9. <RecipeBoxContainer recipe={recipe} key={index} />
  10. )).toJS()
  11. }
  12. </div>
  13. );
  14. export default HomePage;

以下是 src/common/containers/HomePageContainer/HomePageContainer.js

  1. import React from 'react';
  2. import { connect } from 'react-redux';
  3. import HomePage from '../../components/HomePage';
  4. export default connect(
  5. (state) => ({
  6. recipes: state.getIn(['recipe', 'recipes']),
  7. }),
  8. (dispatch) => ({
  9. })
  10. )(HomePage);

src/common/components/LoginBox/LoginBox.js 设计我们 LoginBox:

  1. import React from 'react';
  2. import { Form, FormGroup, Button, FormControl, ControlLabel } from 'react-bootstrap';
  3. const LoginBox = ({
  4. email,
  5. password,
  6. onChangeEmailInput,
  7. onChangePasswordInput,
  8. onLoginSubmit
  9. }) => (
  10. <div>
  11. <Form horizontal>
  12. <FormGroup
  13. controlId="formBasicText"
  14. >
  15. <ControlLabel>请输入您的 Email</ControlLabel>
  16. <FormControl
  17. type="text"
  18. onChange={onChangeEmailInput}
  19. placeholder="Enter Email"
  20. />
  21. <FormControl.Feedback />
  22. </FormGroup>
  23. <FormGroup
  24. controlId="formBasicText"
  25. >
  26. <ControlLabel>请输入您的密码</ControlLabel>
  27. <FormControl
  28. type="password"
  29. onChange={onChangePasswordInput}
  30. placeholder="Enter Password"
  31. />
  32. <FormControl.Feedback />
  33. </FormGroup>
  34. <Button
  35. onClick={onLoginSubmit}
  36. bsStyle="success"
  37. bsSize="large"
  38. block
  39. >
  40. 提交送出
  41. </Button>
  42. </Form>
  43. </div>
  44. );
  45. export default LoginBox;

以下是 src/common/containers/LoginBoxContainer/LoginBoxContainer.js

  1. import React from 'react';
  2. import { connect } from 'react-redux';
  3. import LoginBox from '../../components/LoginBox';
  4. import {
  5. authStart,
  6. showSpinner,
  7. setUser,
  8. } from '../../actions';
  9. export default connect(
  10. (state) => ({
  11. email: state.getIn(['user', 'email']),
  12. password: state.getIn(['user', 'password']),
  13. }),
  14. (dispatch) => ({
  15. onChangeEmailInput: (event) => (
  16. dispatch(setUser({ key: 'email', value: event.target.value }))
  17. ),
  18. onChangePasswordInput: (event) => (
  19. dispatch(setUser({ key: 'password', value: event.target.value }))
  20. ),
  21. onLoginSubmit: (email, password) => () => {
  22. dispatch(authStart(dispatch, email, password));
  23. dispatch(showSpinner());
  24. },
  25. }),
  26. (stateProps, dispatchProps, ownProps) => {
  27. const { email, password } = stateProps;
  28. const { onLoginSubmit } = dispatchProps;
  29. return Object.assign({}, stateProps, dispatchProps, ownProps, {
  30. onLoginSubmit: onLoginSubmit(email, password),
  31. });
  32. }
  33. )(LoginBox);

src/common/components/LoginPage/LoginPage.js,当 spinnerVisible 为 true 会显示 spinner:

  1. import React from 'react';
  2. import { Grid, Row, Col, Image } from 'react-bootstrap';
  3. import LoginBoxContainer from '../../containers/LoginBoxContainer';
  4. const LoginPage = ({
  5. spinnerVisible,
  6. }) => (
  7. <div>
  8. <Row className="show-grid">
  9. <Col xs={6} xsOffset={3}>
  10. <LoginBoxContainer />
  11. { spinnerVisible === true ?
  12. <Image src="/static/images/loading.gif" /> :
  13. null
  14. }
  15. </Col>
  16. </Row>
  17. </div>
  18. );
  19. export default LoginPage;

以下是 src/common/containers/LoginPageContainer/LoginPageContainer.js

  1. import React from 'react';
  2. import { connect } from 'react-redux';
  3. import LoginPage from '../../components/LoginPage';
  4. export default connect(
  5. (state) => ({
  6. spinnerVisible: state.getIn(['ui', 'spinnerVisible']),
  7. }),
  8. (dispatch) => ({
  9. })
  10. )(LoginPage);

真正设计我们内部的食谱, src/common/components/RecipeBox,使用者登入的话可以修改和删除食谱:

  1. import React from 'react';
  2. import { Grid, Row, Col, Image, Thumbnail, Button } from 'react-bootstrap';
  3. const RecipeBox = (props) => {
  4. return(
  5. <Col xs={6} md={4}>
  6. <Thumbnail src={props.recipe.get('imagePath')} alt="242x200">
  7. <h3>{props.recipe.get('name')}</h3>
  8. <p>{props.recipe.get('description')}</p>
  9. {
  10. props.isAuthorized === true ? (
  11. <p>
  12. <Button bsStyle="primary" onClick={props.onDeleteRecipe(props.recipe.get('_id'))}>删除</Button>&nbsp;
  13. <Button bsStyle="default" onClick={props.onUpadateRecipe(props.recipe.get('_id'))}>修改</Button>
  14. </p>)
  15. : null
  16. }
  17. </Thumbnail>
  18. </Col>
  19. );
  20. }
  21. export default RecipeBox;

以下是 src/common/containers/RecipeBoxContainer/RecipeBoxContainer.js

  1. import React from 'react';
  2. import { connect } from 'react-redux';
  3. import RecipeBox from '../../components/RecipeBox';
  4. import { browserHistory } from 'react-router';
  5. import {
  6. deleteRecipe,
  7. setRecipe,
  8. setUi
  9. } from '../../actions';
  10. export default connect(
  11. (state) => ({
  12. isAuthorized: state.getIn(['user', 'isAuthorized']),
  13. recipes: state.getIn(['recipe', 'recipes']),
  14. }),
  15. (dispatch) => ({
  16. onDeleteRecipe: (recipeId) => () => (
  17. dispatch(deleteRecipe(dispatch, recipeId))
  18. ),
  19. onUpadateRecipe: (recipes) => (recipeId) => () => {
  20. const recipeIndex = recipes.findIndex((_recipe) => (_recipe.get('_id') === recipeId));
  21. const recipe = recipeIndex !== -1 ? recipes.get(recipeIndex) : undefined;
  22. dispatch(setRecipe({ keyPath: ['recipe'], value: recipe }));
  23. dispatch(setRecipe({ keyPath: ['recipe', 'id'], value: recipeId }));
  24. dispatch(setUi({ key: 'isEdit', value: true }));
  25. browserHistory.push('/share?recipeId=' + recipeId);
  26. },
  27. }),
  28. (stateProps, dispatchProps, ownProps) => {
  29. const { recipes } = stateProps;
  30. const { onUpadateRecipe } = dispatchProps;
  31. return Object.assign({}, stateProps, dispatchProps, ownProps, {
  32. onUpadateRecipe: onUpadateRecipe(recipes),
  33. });
  34. }
  35. )(RecipeBox);

设计我们分享食谱页面,这边我们把编辑食谱和新增分享一起共用了同一个 components,差别在于我们会判断 UI State 中的 isEdit, 决定相应处理方式。在中 src/common/components/ShareBox/ShareBox.js,可以让使用者登入的后修改和删除食谱:

  1. import React from 'react';
  2. import { Form, FormGroup, Button, FormControl, ControlLabel } from 'react-bootstrap';
  3. const ShareBox = (props) => {
  4. return (<div>
  5. <Form horizontal>
  6. <FormGroup
  7. controlId="formBasicText"
  8. >
  9. <ControlLabel>请输入食谱名称</ControlLabel>
  10. <FormControl
  11. type="text"
  12. placeholder="Enter text"
  13. defaultValue={props.name}
  14. onChange={props.onChangeNameInput}
  15. />
  16. <FormControl.Feedback />
  17. </FormGroup>
  18. <FormGroup
  19. controlId="formBasicText"
  20. >
  21. <ControlLabel>请输入食谱说明</ControlLabel>
  22. <FormControl
  23. componentClass="textarea"
  24. placeholder="textarea"
  25. defaultValue={props.description}
  26. onChange={props.onChangeDescriptionInput}
  27. />
  28. <FormControl.Feedback />
  29. </FormGroup>
  30. <FormGroup
  31. controlId="formBasicText"
  32. >
  33. <ControlLabel>请输入食谱图片网址</ControlLabel>
  34. <FormControl
  35. type="text"
  36. placeholder="Enter text"
  37. defaultValue={props.imagePath}
  38. onChange={props.onChangeImageUrl}
  39. />
  40. <FormControl.Feedback />
  41. </FormGroup>
  42. <Button
  43. onClick={props.onRecipeSubmit}
  44. bsStyle="success"
  45. bsSize="large"
  46. block
  47. >
  48. 提交送出
  49. </Button>
  50. </Form>
  51. </div>);
  52. };
  53. export default ShareBox;

以下是 src/common/containers/ShareBoxContainer/ShareBoxContainer.js

  1. import React from 'react';
  2. import { connect } from 'react-redux';
  3. import ShareBox from '../../components/ShareBox';
  4. import {
  5. addRecipe,
  6. updateRecipe,
  7. showSpinner,
  8. setRecipe,
  9. } from '../../actions';
  10. export default connect(
  11. (state) => ({
  12. recipes: state.getIn(['recipe', 'recipes']),
  13. recipeId: state.getIn(['recipe', 'recipe', 'id']),
  14. name: state.getIn(['recipe', 'recipe', 'name']),
  15. description: state.getIn(['recipe', 'recipe', 'description']),
  16. imagePath: state.getIn(['recipe', 'recipe', 'imagePath']),
  17. isEdit: state.getIn(['ui', 'isEdit']),
  18. }),
  19. (dispatch) => ({
  20. onChangeNameInput: (event) => (
  21. dispatch(setRecipe({ keyPath: ['recipe', 'name'], value: event.target.value }))
  22. ),
  23. onChangeDescriptionInput: (event) => (
  24. dispatch(setRecipe({ keyPath: ['recipe', 'description'], value: event.target.value }))
  25. ),
  26. onChangeImageUrl: (event) => (
  27. dispatch(setRecipe({ keyPath: ['recipe', 'imagePath'], value: event.target.value }))
  28. ),
  29. onRecipeSubmit: (recipes, recipeId, name, description, imagePath, isEdit) => () => {
  30. if (isEdit === true) {
  31. dispatch(updateRecipe(dispatch, recipeId, name, description, imagePath));
  32. dispatch(showSpinner());
  33. } else {
  34. dispatch(addRecipe(dispatch, name, description, imagePath));
  35. dispatch(showSpinner());
  36. }
  37. },
  38. }),
  39. (stateProps, dispatchProps, ownProps) => {
  40. const { recipes, recipeId, name, description, imagePath, isEdit } = stateProps;
  41. const { onRecipeSubmit } = dispatchProps;
  42. return Object.assign({}, stateProps, dispatchProps, ownProps, {
  43. onRecipeSubmit: onRecipeSubmit(recipes, recipeId, name, description, imagePath, isEdit),
  44. });
  45. }
  46. )(ShareBox);

单纯的 SharePage(src/common/components/SharePage/SharePage.js)页面:

  1. import React from 'react';
  2. import { Grid, Row, Col } from 'react-bootstrap';
  3. import ShareBoxContainer from '../../containers/ShareBoxContainer';
  4. const SharePage = () => (
  5. <div>
  6. <Row className="show-grid">
  7. <Col xs={6} xsOffset={3}>
  8. <ShareBoxContainer />
  9. </Col>
  10. </Row>
  11. </div>
  12. );
  13. export default SharePage;

以下是 src/common/containers/SharePageContainer/SharePageContainer.js

  1. import React from 'react';
  2. import { connect } from 'react-redux';
  3. import SharePage from '../../components/SharePage';
  4. export default connect(
  5. (state) => ({
  6. }),
  7. (dispatch) => ({
  8. })
  9. )(SharePage);

恭喜你成功抵达终点!若一切顺利,在终端机打上 $ npm start,你将可以在浏览器的 http://localhost:3000 看到自己的成果!

用 React + Redux + Node(Isomorphic)开发一个食谱分享网站

总结

本章整合过去所学和添加一些后端资料库知识开发了一个可以登入会员并分享食谱的社群网站!快把你的成果和你的朋友分享吧!觉得意犹未尽?别忘了附录也很精采!最后,再次谢谢读者们支持我们一路走完了 React 开发学习之旅!然而前端技术变化很快,唯有不断自我学习才能持续成长。笔者才疏学浅,撰写学习心得或有疏漏,若有任何建议或提醒都欢迎和我说,大家一起加油:)

延伸阅读

  1. joshgeller/react-redux-jwt-auth-example
  2. <a href="https://medium.com/@rajaraodv/securing-react-redux-apps-with-jwt-tokens-fcfe81356ea0#.5hfri5j5m">Securing React Redux Apps With JWT Tokens
  3. Adding Authentication to Your React Native App Using JSON Web Tokens
  4. Authentication in React Applications, Part 2: JSON Web Token (JWT)
  5. Node.js 身份认证:Passport 入门
  6. react-bootstrap compatibility #83
  7. How to authenticate routes using Passport? #725
  8. Isomorphic React Web App Demo with Material UI
  9. react-router/examples/auth-flow/
  10. redux-promise
  11. <a href="http://qiita.com/takaki@github/items/42bddf01d36dc18bdc8e">How to use redux-promise
  12. Authenticate a Node.js API with JSON Web Tokens
  13. 3 JavaScript ORMs You Might Not Know
  14. lynndylanhurley/redux-auth
  15. How to avoid getting error ‘localStorage is not defined’ on server in ReactJS isomorphic app?
  16. Where to Store your JWTs – Cookies vs HTML5 Web Storage
  17. What is the difference between server side cookie and client side cookie? [closed]
  18. Cookies vs Tokens. Getting auth right with Angular.JS
  19. Cookies vs Tokens: The Definitive Guide
  20. joshgeller/react-redux-jwt-auth-example
  21. Programmatically navigate using react router
  22. withRouter HoC (higher-order component) v2.4.0 Upgrade Guide

License

MIT, Special thanks Loading.io