用 React + Redux + Node(Isomorphic JavaScript)開發食譜分享網站

前言

如果你是從一開始跟著我們踏出 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

用 React + Redux + Node(Isomorphic)開發一個食譜分享網站

動手實作

首先我們先進行 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. @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. @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

| 勘誤、提問或許願 |