Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. //router.js
  2. import React from 'react'
  3. import { matchPath, StaticRouter } from 'react-router-dom';
  4. import { renderToString } from 'react-dom/server';
  5. import routes from './routes';
  6. import App from '../build-client/App.js';
  7.  
  8. function GetMatchingRoute(url)
  9. {
  10. for (let i=0; i<routes.length; i++)
  11. {
  12. let route=routes[i];
  13. let match=matchPath(url, {path:route, exact:true});
  14. if (match)
  15. {
  16. return match;
  17. }
  18. }
  19. return null;
  20.  
  21. }
  22. export default function router(req, res){
  23. const match=GetMatchingRoute(req.url);
  24. //const match = routes.reduce((acc, route)=>{return matchPath(req.url, {path: route, exact:true}) || acc}, null);
  25. if (!match)
  26. {
  27. res.status(404).send('page not found');
  28. return;
  29. }
  30. const context={}
  31. const router=(
  32. <div>
  33. hello world
  34. <StaticRouter context={context} location={req.url}>
  35. <App location={req.url}/>
  36. </StaticRouter>
  37. </div>
  38. )
  39. let html=renderToString(router);
  40. res.status(200).send(html);
  41. }
  42. //-------------------------------------------------------------------------------------------
  43. //app.js
  44. import React, { Component } from 'react';
  45. import Home from './Home'
  46. import Stuff0 from './Stuff0'
  47. import Stuff1 from './Stuff1'
  48. import {Switch, Route, Link} from 'react-router-dom'
  49. //import './styles/App.css';
  50.  
  51. class App extends Component {
  52. render() {
  53. return (
  54. <div>
  55. <ul>
  56. <li><Link to="/">Home</Link></li>
  57. <li><Link to="/Stuff0">Stuff0</Link></li>
  58. <li><Link to="/Stuff1">Stuff1</Link></li>
  59. </ul>
  60. <Switch>
  61. <Route exact path="/" component={Home}>Home</Route>
  62. <Route path="/Stuff0" component={Stuff0}>Stuff0</Route>
  63. <Route path="/Stuff1" component={Stuff1}>Stuff1</Route>
  64. </Switch>
  65. </div>
  66. );
  67. }
  68. }
  69. export default App;
  70. //--------------------------------------------------------------------------------------------
  71. //server.js
  72. import express from 'express';
  73. import Path from 'path'
  74. import router from './router'
  75.  
  76. const app = express();
  77. const port = 3500;
  78.  
  79. app.get('*', router)
  80.  
  81. app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement