Reputation: 616
I'm trying to access the id
of a user when rendering its profile page by accessing the route /users/:id
in app.js
. This route his handled by the middleware app.use('/users/:id', userProfile);
.
The error I'm getting is 404 Error: Not Found
. According to what is returned to the client, it's handled by the middleware in app.js
following the routes declaration with the comment 'catch 404 and forward to error handler'. I'm not sure what I've done wrong. Where's the error in my code?
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}
Upvotes: 0
Views: 2673
Reputation: 10687
In your app.js, change
app.use('/users/:id', userProfile);
to
app.use('/users', userProfile);
since you've already specified /:id
, inside your userProfile.js
Upvotes: 4