【问题标题】:Node express 404 error HTTP status codeNode express 404错误HTTP状态码
【发布时间】:2015-08-29 23:09:48
【问题描述】:

我已将我的 node Express 应用程序精简到最低限度。我什至不再定义路线。 当我去任何路线时,例如localhost:3000/sdfsdf,我得到了预期的输出:

{“消息”:“未找到”,“错误”:{“状态”:404}}

但是响应的 HTTP 状态代码是 200。我希望它是 404。 我错过了什么?

var express = require('express');
var path = require('path');

var app = express();
app.use(express.static(path.join(__dirname, 'public')));

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// development error handler
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        //res.set('Content-Type', 'application/json');
        res.status(err.status || 500);
        res.status('error').json({
            message: err.message,
            error: err
        });
    });
}
// production error handler
app.use(function(err, req, res, next) {
    res.set('Content-Type', 'application/json');
    res.status(err.status || 500);
    res.status('error').json({
        message: err.message,
        error: {'env': 'prod'}
    });
});

module.exports = app;

【问题讨论】:

    标签: node.js express http-status-code-404


    【解决方案1】:
    res.status(err.status || 500);
    res.status('error').json({
    

    你终于用“error”覆盖了res.statuscode。改为

    res.status(err.status || 500);
    res.json({
    

    【讨论】:

    • 非常感谢。我没有看到。 :-)
    猜你喜欢
    • 1970-01-01
    • 2018-11-18
    • 2014-10-24
    • 1970-01-01
    • 2017-03-27
    • 2021-06-19
    • 2016-02-07
    • 1970-01-01
    • 2021-05-25
    相关资源
    最近更新 更多