【问题标题】:How can I handle routing with express when I use a static site?使用静态站点时如何使用 express 处理路由?
【发布时间】:2019-11-11 14:37:47
【问题描述】:

当用户访问 mydomain.com/game 时,我希望用户看到我的公用文件夹中显示的内容。当我这样做时,这完全正常:

app.use('/game', express.static('public'))

问题是我想从 URL 中提取一些信息,但是由于我不知道在使用静态站点时如何继续路由,所以我无法提取任何信息。例如,如果用户输入 mydomain.com/game/123,我想检索 123,但仍将该人路由到我的公共文件夹,就像 mydomain.com/game 一样。

关于如何处理这个问题的任何想法?

【问题讨论】:

    标签: javascript html node.js express http


    【解决方案1】:

    如果您使用的是 react 静态文件,并且您想使用 express 提供所有 react 路由,那么您必须执行以下操作-

    1.首先你必须在你的 react 文件夹中运行命令

    npm run build
    

    这将在 react 应用程序中创建您的构建文件夹,其中包含一个您必须通过 express 提供的 index.html 文件。 现在来到你的 server.js 文件并写在那里

    const express = require('express');
    var path = require('path');
    
    const app = express();
    app.use(express.static(path.join(__dirname, 'client/build')));
    app.get('*', (req,res) => {
        res.sendFile(path.join(__dirname+'/client/build/index.html'));
    });
    const port = process.env.PORT || 5000;
    app.listen(port, () => console.log(`Server up and running on port ${port} !`));
    

    【讨论】:

      【解决方案2】:

      尝试使用两个中间件:第一个是你的静态中间件,第二个是后备,id (123)

      app.use('/game', express.static('public'));
      app.use('/game/:id', function(req, res) { // when static not found, it passed to this middleware, this process it
          console.log('your id', req.params.id);
          res.send('ok');
      });
      

      【讨论】:

        【解决方案3】:

        这在类似情况下对我有用

        app.use('/game/:id', (req, res) => {
          // do something with id
          res.redirect(302, '/game');
        }
        

        【讨论】:

        • 这很好用!出于某种原因,标记正确答案有时间限制。时间到了我会做的。
        猜你喜欢
        • 1970-01-01
        • 2015-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-19
        • 1970-01-01
        • 1970-01-01
        • 2014-02-18
        • 2021-03-29
        相关资源
        最近更新 更多