如何在Express应用程序上修复404 NotFoundError

时间:2019-04-14 23:12:36

标签: node.js express

我正在学习nodejs,并尝试使用mongodb设置一个简单的api,在运行代码后,它将引发NotFound错误并创建空集合。

模式

    var mongoose = require('mongoose');

var userSchema = new mongoose.Schema({
    firstName: String,
    lastName: String,
    email: {type: String, required: true, match: /.+@+\..+/, index: true},
    username: {type: String, trim: true, unique: true, require: true},
    password: {type: String, validate: [function (password) {
            return password.length >= 6;
        }, 'Password length should be longer']},

    createdOn: { type: Date, default: Date.now},
    website: {
        type: String,
        get: function (url) {
            if (!url){
                return url;
            } else if (url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0){
                url = 'http://' + url;
            }
            return url;
        }
    },
    role: {type: String, enum: ['Owner', 'Admin', 'User']}

});


userSchema.virtual('fullName').get(function () {
    return this.firstName  + ' ' + this.lastName;
}).set(function (fullName) {
    var splitName = fullName.split(' ');
    this.firstName = splitName[0] || '';
    this.lastName = splitName[1] || '';
});


userSchema.statics.findOneByUsername = function(username, callback){

    this.findOne({username: new RegExp(username, 'i')}, callback);
};


userSchema.method.authenticate = function(password){
    return this.password === password;
};

userSchema.set('toJSON', {getters: true, virtuals: true});

mongoose.model('User', userSchema);

逻辑控制器

    const User = require('mongoose').model('User');


    exports.create = function (req, res, next) {
    var user = new User({
        firstName: req.body.firstName,
        lastName: req.body.lastName,
        email: req.body.email,
        username: req.body.username,
        password: req.body.password
    });

    user.save((err) => {
        if (err) {
            return next(err);
        } else {
            res.json(user);
        }
    });
};

路线

var router = require('express').Router();
var user = require('../controllers/user');

/* GET users listing. */
router.post('/users', user.create);

module.exports = router;

错误消息

<h1>Not Found</h1>
        <h2>404</h2>
        <pre>NotFoundError: Not Found
    at C:\tmp\meanapp\app.js:38:8
    at Layer.handle [as handle_request] (C:\tmp\meanapp\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\tmp\meanapp\node_modules\express\lib\router\index.js:317:13)
    at C:\tmp\meanapp\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\tmp\meanapp\node_modules\express\lib\router\index.js:335:12)
    at next (C:\tmp\meanapp\node_modules\express\lib\router\index.js:275:10)
    at C:\tmp\meanapp\node_modules\express\lib\router\index.js:635:15

Express应用 我已经检查了第38行:但无法找出问题,进行了全新安装,但仍然遇到相同的错误,因此不知道我在做什么错。将不胜感激。预先感谢

var config = require('./app_api/env/config');
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session =require('express-session');


require('./app_api/models/user');


var indexRouter = require('./app_api/routes/index');
var usersRouter = require('./app_api/routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'app_api/views'));
app.set('view engine', 'pug');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  saveUninitialized: true,
  resave: true,
  secret: config.sessionSecret
}));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

0 个答案:

没有答案