What's wrong with this ReactRouter.match() implementation?

后端 未结 1 1057
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-19 04:20

I\'m trying to serve up React from my server via express.

The error I\'m getting, though, when I hit localhost:3000 is:

TypeError: (0 , _reactRouter.         


        
1条回答
  •  借酒劲吻你
    2021-01-19 04:33

    Your code looks correct if you used react router prior to v4, but react-router v4 has breaking changes throughout the codebase, including the method for server rendering. In v4, there is a new component specifically for server rendering - StaticRouter.

    Your code should looks something like this with v4:

    import path from "path";
    import { Server } from "http";
    import Express from "express";
    import React from "react";
    import { renderToString } from "react-dom/server";
    import { StaticRouter } from "react-router";
    import App from "./app";
    import NotFoundPage from "./components/NotFoundPage";
    
    // Initialize the express server, and tell it to use ejs
    const app = new Express();
    const server = new Server(app);
    app.set("view engine", "ejs");
    app.set("views", path.join(__dirname, "views"));
    
    // Tell express where the static assets are
    app.use(Express.static(path.join(__dirname, "static")));
    
    app.get("*", (req, res) => {
      // This context object contains the results of the render
      const context = {};
    
      const html = renderToString(
        
          
        
      );
      res.status(200).send(html);
    });
    
    const port = process.env.PORT || 3000;
    const env = process.env.NODE_ENV || "production";
    server.listen(port, err => {
      if (err) {
        return console.error(err);
      }
      console.info(`Server running on http://localhost:${port} [${env}]`);
    });
    

    Here is a really nice annotated article by EbayTech showing how to set up an app with StaticRouter(for server) and BrowserRouter(for client)

    0 讨论(0)
提交回复
热议问题