使用 NextJS 时 ExpressJS 中间件不工作 Link

ExpressJS middleware not working when using NextJS Link

我在 Next 中使用 Express 路由,在下面的示例中,/a 应该可供授权人员访问,而 /b 是 public。

... other imports...
const app = next({ isDev })
const handle = app.getRequestHandler()

async function isAuth(req, res, next) {
  const token = req.header('x-Auth-Token');
  if (!token) return res.status(401).send('Access denied. No token provided.');

  req.user = 'Connected!';
  next();
}

app.prepare().then(() => {
  const server = express()

  server.get('/a', isAuth, async (req, res) => {
    return app.render(req, res, '/a', req.query)
  })

  server.get('/b', async (req, res) => {
    return app.render(req, res, '/b', req.query)
  })

  server.all('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

非常简单明了,现在我正确地使用浏览器的 url 栏 except/a 上拒绝了我的访问我使用 /b 页面中的 <Link href="/a">。然后页面显示隐藏内容,我的访问没有被检查...为什么?我该如何解决这个问题?

可以使用此 Github link 重现此问题,您只需像我在上面的示例中所做的那样添加 isAuth 示例。

这是 Next.JS Link 工作原理的一部分。它已经预取了即将到来的站点的源代码,而没有获取真实端点,因此您需要针对当前情况实施前端和后端检查。

如需更多信息,请随时关注 Next.JS Github 问题中的讨论:Github NextJs Restricted Links。它清楚地解释了如何处理这种情况。