首页 > 解决方案 > 未找到 404 NotFoundError:未找到 - Node.js Express

问题描述

当我在终端 (macOS) (DEGUG=app:* npm run devstart) 中运行应用程序时,它工作正常(服务器在端口 3000 +0ms 上侦听)。但是,当我在浏览器中打开 localhost 时,它只会显示“Welcome Express”页面,当我转到特定路线时,它会显示 NotFoundError: Not Found。

我一直以这种结构为指导(在https://expressjs.com/en/starter/faq.html上)。

app.use(function (req, res, next) {
  res.status(404).send("Sorry can't find that!")
})

这是我在我的一个控制器上的代码的一部分,我在其中使用 404 响应:

var CCSelectionCriterion = require('../models/ccselectioncriterion');
var async = require('async');

const { body, validationResult } = require('express-validator/check');
const { sanitizeBody } = require('express-validator/filter');

// Display detail page for a specific CCSelectionCriterion.
exports.ccselectioncriterion_detail = function (req, res, next) {

    CCSelectionCriterion.findById(req.params.id)
        .exec(function (err, ccselectioncriterion) {
            if (err) { return next(err); }
            if (ccselectioncriterion==null) { // No results.
                var err = new Error('CC Selection Criterion not found');
                err.status = 404;
                return next(err);
            }
            // Successful, so render.
            res.render('ccselectioncriterion_detail', {title: 'CC Selection Criterion Detail', ccselectioncriterion: ccselectioncriterion});
        })
};

非常感谢。

标签: javascriptnode.jsexpress

解决方案


推荐阅读