Advertisement
Guest User

Untitled

a guest
Aug 18th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. import express from "express";
  2. import React from "react";
  3. import { renderToString } from "react-dom/server";
  4. import { StaticRouter as Router } from "react-router-dom";
  5. import path from "path";
  6. import App from "./client/app";
  7. const app = express();
  8. const port = 3000;
  9. import Routes from "./routes";
  10.  
  11. const HTML = (req, context) => {
  12. const body = renderToString(
  13. <Router location={req.url} context={context}>
  14. <App />
  15. </Router>
  16. );
  17. return `<html>
  18. <head>
  19. <title>React Basic SSR</title>
  20. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  21. </head>
  22. <body style="margin:0;">
  23. <div id="app">
  24. ${body}
  25. </div>
  26. <script src="client.js"></script>
  27. </body>
  28. </html>`;
  29. };
  30.  
  31. const context = {};
  32.  
  33. app.use(express.static("dist"));
  34.  
  35. app.get("*", (req, res) => {
  36. return res.send(HTML({ url: "/404" }, context));
  37. });
  38.  
  39. Routes.forEach(route => {
  40. app.get(route.url, (req, res) => {
  41. return res.send(HTML(req, context));
  42. });
  43. });
  44.  
  45. app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement