【问题标题】:Refreshing the page using Node.js / Express?使用 Node.js / Express 刷新页面?
【发布时间】:2021-04-03 21:20:43
【问题描述】:

用户连接后,我需要在我的小型 Node 和 Express 应用程序中刷新页面。我在第二个 sn-p 中尝试了res.redirect('index.html'),但是当我尝试连接到根 URL 时它会引发错误。

以下代码在用户连接到根 URL 时运行:

app.get('/', (req, res) => {
  res.redirect('/index.html')
  app.use(express.static(path.join(__dirname, 'public')))
});

我检测到用户何时连接:

io.on('connection', (socket) => {}

提前致谢!

【问题讨论】:

  • 对于初学者,app.use(express.static(path.join(__dirname, 'public'))) 不应该在另一条路线内。这需要在与您的app.get() 相同的级别上上升。因为你只是在每次/ 路由被命中时添加一个新的重复中间件。随着时间的推移,这将占用越来越多的内存。
  • 你得到什么错误?您是否为/index.html 安装了路由?
  • @jfriend00 我已经修好了路线,非常感谢您的建议。我得到的错误是 TypeError: Cannot read property 'redirect' of undefined
  • 你是从哪一行代码中得到这个错误的?

标签: javascript node.js express npm


【解决方案1】:
app.get('/', (req, res) => {
    //  res.redirect('back');
    // OR
  res.redirect(req.get('referer'));
  app.use(express.static(path.join(__dirname, 'public')))
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 2016-06-30
    • 1970-01-01
    • 2017-06-14
    • 2018-02-04
    • 2018-07-02
    相关资源
    最近更新 更多