我正在尝试通过访问id
中的路由/users/:id
来呈现其个人资料页面时访问用户的app.js
。这条路由由中间件app.use('/users/:id', userProfile);
处理。
我得到的错误是404 Error: Not Found
。根据返回给客户端的内容,它由app.js
中的中间件在路由声明之后处理,并带有注释'catch 404并转发到错误处理程序'。我不确定我做错了什么。我的代码中的错误在哪里?
var express = require('express');
var stormpath = require('express-stormpath');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// include routes
var mainPage = require('./routes/mainPage');
var users = require('./routes/user');
var userProfile = require('./routes/userProfile');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// routes
app.use('/', mainPage);
app.use('/api/users', users);
app.use('/users/:id', userProfile);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
var User = require('../models').sequelize.models.User;
var express = require('express');
var router = express.Router();
router.get('/:id', function(req, res, next) {
User.findById({
id: req.params.id
})
.then(function(user) {
if(!user) {
var err = new Error('Not Found');
err.status = 404;
next(err);
} else
res.render('userProfile', { user: user });
});
});
module.exports = router;
extends layout
block content
#page-wrapper
.container
h2 User #{user.id}
答案 0 :(得分:4)
在您的app.js中,更改
app.use('/users/:id', userProfile);
到
app.use('/users', userProfile);
因为您已经在userProfile.js
中指定了/:id