ExpressJS 由 ejs 和 React 前端混合支持

ph-*_*ett 7 javascript ejs node.js express reactjs

我目前有一个带有 Express 后端的 NodeJS 应用程序,并且所有前端都是用 EJS 实现的。当前的示例路线如下所示:

router.get("/:name&:term", function(req, res) {
    Course.find({ courseName: req.params.name, courseTerm: req.params.term }).populate("students")
    .exec(function(err, foundCourse) {
        if (err) {
            console.log(err);
        } else {
            console.log(foundCourse)
            res.render("courses/show", { course: foundCourse });        
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

我已经按照上面的示例路线实现了网站的许多页面。所以结构看起来像这样:

localhost:3000
-/courses
   -/show
   -/review
-/professors
   -/show
   -/rating
...
Run Code Online (Sandbox Code Playgroud)

但我最近参加了 React 课程,并希望将 React 用于新页面,例如localhost:3000/groups

有没有办法在某些页面上使用 React,并且仍然拥有我当前拥有的 EJS 页面?或者我是否必须将所有 EJS 页面重写为 React 组件?我对网络开发还很陌生,所以任何建议将不胜感激。

根据我的理解,我必须让 React 应用程序仅捕获某些请求/路由,但我不太确定该怎么做。

mar*_*lin 3

为了彻底回答这个问题,我必须写一本小书,所以我只展示代码在客户端呈现的基本情况。我还假设您知道如何将 jsx 转换为 js,因此我会将所有 React 文件视为已转换(即全部<>转换为React.createElement())。

首先,您必须创建一条将由react( /groups)处理的路线,(我假设您将使用一些数据进行渲染,如示例中所示):

router.get("groups/:name&:term", function(req, res) {
    Groups.find({ groupName: req.params.name, courseTerm: req.params.term }).populate("students")
    .exec(function(err, foundGroup) {
        if (err) {
            console.log(err);
        } else {
            // here will be the react rendering code        
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

假设你有react代码index.js,你必须将它添加到html代码以及应用程序所需的数据中:

router.get("groups/:name&:term", function(req, res) {
    Groups.find({ groupName: req.params.name, courseTerm: req.params.term }).populate("students")
    .exec(function(err, foundGroup) {
        if (err) {
            console.log(err);
        } else {
            res.send(`<html>
               <head>
                 <script>
                   const initialData=${JSON.stringify(foundGroup)};
                 </script>
               </head>
               <body>
                 <div id="react-root"></div>
                 <script src="index.js"></script>
               </body>
            </html>`);
                    
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

App应该像这样使用数据:

React.render(<App initialData={initialData}/>, document.getElementById("react-root");
Run Code Online (Sandbox Code Playgroud)

这应该会让你的反应代码启动并运行。更进一步,您可以react-dom/server在服务器上预渲染 html,并混合 ejs 文件作为模板,在其中注入 React 代码以利用现有的代码库。