【问题标题】:next() and sending 404 pagenext() 并发送 404 页面
【发布时间】:2017-12-17 12:58:58
【问题描述】:

我目前正在尝试发送一个 .pug 文件的 404 页面,只要 ID 参数不在数据库中。我在 api 路由中调用 next(),当我在 elastics 搜索回调中调用时,它会抛出一个 page not found 错误以及两条 Cant set header after they are sent 消息。当我在外面调用next() 时,它只会显示 404 错误消息而不是标题消息。我不确定它为什么这样做。

//这样做会正确发送404页面。

app.get('/redirect/:id', function(req, res, next) {
        let found = false;

        if (!found) {
           return next();
        }

});

//但是我需要检查一个ID是否存在然后抛出404,但是这样做是行不通的,我会不断收到无法设置标题和404消息的错误。

app.get('/redirect/:id', function(req, res, next) {

    search.byId(req.params.id, (err, card) => {
        if (err) log.log(err);

        if (!card || card === undefined) {
            return next();
        }
    });

});

【问题讨论】:

  • 为什么是next()?你完成了。 res.status(404).end(); 将返回您的 404
  • 好的,我试过了,但它仍然没有发送我的 404 页面。在 shell 中,set headers 错误消息将不再显示,但 404 错误页面未找到也不会显示。它确实显示了一堆 GET 请求正在以 304 状态发生
  • 什么叫你的终点?邮递员?
  • 弹性搜索。 search.byId 是一种弹性搜索方法
  • 你的/redirect/:id 叫什么?弹性搜索?

标签: javascript node.js http-status-code-404 next


【解决方案1】:

在 express 中,next() 函数用于将控制权传递给下一个中间件。 Using Express Middleware

app.use('/user/:id', function (req, res, next) {
  console.log('Request URL:', req.originalUrl)
  next()
}, function (req, res, next) {
  console.log('Request Type:', req.method)
  next()
})

在上面的示例中,当第一个 next() 被调用时,第二个 函数 (req, res, next)(在 express.js 中,该函数称为中间件)被执行并注销请求类型。 所以 next 在这里对您没有帮助,因为您没有构建中间件堆栈。 如果您只想渲染 404 页面,请阅读 How to redirect 404 errors to a page in ExpressJS?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2023-03-05
    • 2020-11-13
    • 1970-01-01
    • 2015-03-02
    相关资源
    最近更新 更多