req.body undefined multipart - javascript

I have a problem with my POST request on multipart (form-data). All ideas in other topics don't work.
I use express, multer and postman
I totally delete body-parser
Uploading files works but accessing the data with a key don't work.
When I try console.log(req.body); I obtain undefined
This is my code:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cors=require('cors');
//var index = require('./routes/index');
//var users = require('./routes/users');
var UsersDB=require('./routes/UsersDB');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(cors());
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
//app.use('/', index);
//app.use('/users', users);
app.use('/Users',UsersDB);
// 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 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;
UsersDB.js
var express = require('express');
var router = express.Router();
var Users=require('../models/Users');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + ".png")
}
});
var upload = multer({ storage: storage }).single('avatar');
//** POST ** ROUTE : http://localhost:3000/Users/
router.post('/',function(req,res,next)
{
console.log(req.body.firstName);
/*
Users.addUsers(req.body,function(err,count)
{
if(err)
{
res.json(err);
}
else
{
res.json(req.body);//or return count for 1 & 0
}
});
*/
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading
return
}
// Everything went fine
})
});
module.exports=router;
Error on Postman:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1>Cannot read property 'firstName' of undefined</h1>
<h2></h2>
<pre>TypeError: Cannot read property 'firstName' of undefined
at /mnt/c/Users/Elodie/Desktop/server/routes/UsersDB.js:69:25
at Layer.handle [as handle_request] (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/layer.js:95:5)
at next (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/layer.js:95:5)
at /mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/index.js:335:12)
at next (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/index.js:174:3)
at router (/mnt/c/Users/Elodie/Desktop/server/node_modules/express/lib/router/index.js:47:12)</pre>
</body>
</html>

Since you're using multer to parse the request body, you're going to need to invoke multer prior to accessing req.body. The way you are currently using multer, it will extract the information from the request to process the file but will not be part of the middleware stack so you don't get the benefit of the body parsing prior to your route being called.
Add the multer middleware into the route signature and so it the request body will be parsed by multer prior to the route callback being invoked. For example like this
router.post('/', upload.single('avatar'), (req, res, next) => {
console.log(req.body.firstName)
})

Related

Express Route 404

I'm having trouble with my node.js express routes. I'm really new to it and I can't see my mistake. I'm always getting a 404 Error when requesting localhost:2700/api/subs, but I think that my route is correct, isn't it? Can anybody see a mistake?
Beginning of the Error Message:
Error: Not Found
at ****/app.js:45:13
at Layer.handle [as handle_request] (****/node_modules/express/lib/router/layer.js:95:5)
Here is the app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
const mongoose = require('mongoose');
// establish connection to the Database
mongoose.connect('mongodb://localhost/test', {
useMongoClient: true
});
mongoose.connection.once('open', function() {
console.log('Connection to Database has been established..');
}).on('error', function(error){
console.log(error);
});
var index = require('./routes/index');
var users = require('./routes/users');
Subscriber = require('./routes/subscriber.js');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
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')));
app.use('/', index);
app.use('/users', users);
// 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 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');
});
app.get('/api/subs', function(req, res){
Subscriber.getSubscribers(function(err, subscribers){
if(err){
throw err;
}
res.json(subscribers);
});
});
// ... here is a function which creates the database objects and saves
// them. took it out for better overview....
app.listen(2700, function(){
console.log("Listening on Port 2700")
});
module.exports = app;
and the subscriber.js which is in the subdirectory ./routes:
const mongoose = require('mongoose');
var subscriberSchema = mongoose.Schema({
//seqnr shall go here. dunno how to declare integer x)
nr: Number,
name: String,
email: String,
uLink: String,
anwalt: String
});
var Subscriber = module.exports = mongoose.model('Subscriber', subscriberSchema);
//get Subscriber
module.exports.getSubscribers = function(callback, limit){
Subscriber.find(callback).limit(limit);
};
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
You need to put your 404 app.use after all the other uses, otherwise it will ignore the api/subs after it.
Also, this bit will never run, because it also comes after an api.use that will always throw an error:
// 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');
});
Plus, you really shouldn't be throwing errors for 404s. It should tell the end user the page doesn't exist, but it shouldn't crash your script.
Also I agree with the other answer that says you should move those code blocks into separate router files, but that's more for good practice and structuring than for this particular bug.
Try putting it in a separate file and including it where you do with other routes, before the 404 handler
app.use('/', index);
app.use('/users', users);
So... make a subs.js route
var express = require('express');
var router = express.Router();
Subscriber = require('./routes/subscriber.js');
router.get('/', function(req, res){
Subscriber.getSubscribers(function(err, subscribers){
if(err){
throw err;
}
res.json(subscribers);
});
});
module.exports = router;
Then include it in your app.js
var subs= require('./routes/subs');
...
api.use('/api/subs', subs);
...
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

Node.js express router.post returns 404 not found

My express application seems to return 404 NOT FOUND whenever im using a post request method in my routes file. GET-requests are working fine and i can only see "GET" requests in the console aswell, even if im using a post request.
Is there some missing link between app.js and routes/index.js that might be causing this?
// routes/index.js
router.post('/foo', function (req, res, next) {
res.setHeader('Content-Type', 'application/json');
res.send('You sent: sdadad to Express');
})
// App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var app = express();
var cors = require('cors')
app.use(cors())
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
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')));
app.use('/', index);
// 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 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;
Result:
Not Found 404
Error: Not Found
at C:\Users\willow\Desktop\backend\app.js:29:13
at Layer.handle [as handle_request] (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:317:13)
at C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:275:10)
at C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:635:15
at next (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:260:14)
at Function.handle (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:317:13)
at C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\willow\Desktop\backend\node_modules\express\lib\router\index.js:275:10)
at SendStream.error (C:\Users\willow\Desktop\backend\node_modules\serve-static\index.js:121:7)
What you wanna do should look like this in practice:
// routes/index.js
module.exports = (express) => {
// Create express Router
var router = express.Router();
// add routes
router.route('/foo')
.post((req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send('You sent: sdadad to Express');
});
return router;
}
// App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes')(express); // require routes at routes/index.js
var app = express();
var cors = require('cors')
app.use(cors())
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
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')));
app.use('/', routes);
// 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 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;
What I usually do is create a function that expects express as param like this
(routes/index.js)
module.exports = (express) => {
// Create express Router
var api = express.Router();
// add routes
api.route('/some_endpoint')
.post((req, res) => {
res.json({ message : 'some message' })
});
return api;
}
then I just import this file to my app.js
like this
(app.js)
// set api as a middleware
const api = require('./routes')(express);
app.use('/api/v1', api);
that way I hook up my api and my server.

Uploading images using Express

I am building an REST Api where it contains quite a few images using Express. The project structure is shown below.
And inside the public folder you can see that structure.
I want to upload images and store them inside the img folder. So here is my code.
fileupload.html
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="http://127.0.0.1:3000/fileupload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
and fileupload.js
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
//console.log(multer);
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/img'}));
app.get('fileupload.html', function (req, res) {
res.sendFile( __dirname + "/" + "fileupload.html" );
})
app.post('/fileupload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/img" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at localhost:3000/", host, port)
})
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var url = 'mongodb://localhost:27017/larissaApp';
mongoose.connect(url);
var db = mongoose.connection;
db.on('error',console.error.bind(console,'connection error:'));
db.once('open',function(){
console.log("Connected correctly to server");
});
var routes = require('./routes/index');
var users = require('./routes/users');
var newsRouter = require('./routes/newsRouter');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use( bodyParser.json({limit: '50mb'}) );
app.use(bodyParser.urlencoded({
limit: '50mb',
extended: true,
parameterLimit:50000
}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/news',newsRouter);
// 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;
However after trying to upload an image from the html page,I get a 404 error.
404
Error: Not Found
at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\app.js:40:13
at Layer.handle [as handle_request] (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:317:13)
at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:275:10)
at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:635:15
at next (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:260:14)
at Function.handle (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:317:13)
at C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\express\lib\router\index.js:275:10)
at serveStatic (C:\Users\Theodosios\Desktop\larissa-node\larissaApp\rest-server\node_modules\serve-static\index.js:75:16)
What am I doing wrong?
Thanks,
Theo.
Download the code for Uploading images using Express
File upload with express
Try this.
I modified your js little bit, it works for me without errors.
I've written comments for each line edited.
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
var multer = require('multer');
//console.log(multer);
app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended: false}));
var upload = multer({dest: './img'});// declare multer default path(best to use /tmp for this if on linux)
app.get('fileupload.html', function (req, res) {
res.sendFile(__dirname + "/" + "fileupload.html");
});
app.post('/fileupload', upload.single('file')/*inserted multer middleware for one file*/, function (req, res) {
//Declare variable to easy change
var file = req.file;
// this are correct names for variables of req.file
console.log(file.filename);
console.log(file.path);
console.log(file.mimetype);
// path of file stored
var path = __dirname + '/img/';
// variable for storing path
var filePath = path + file.filename;
//It's better to declare variable first then use it
var response;
fs.readFile(filePath, function (err, data) {
fs.writeFile(path + file.originalname, data, function (err) {
if (err) {
console.log(err);
} else {
response = {
message: 'File uploaded successfully',
filename: file.originalname
};
}
console.log(response);
res.end(JSON.stringify(response));
});
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at localhost:3000/", host, port)
});

Failed to look up '/user/profile' in views directory

I'm trying to build a shopping cart using node.js, express.js and mongodb. I'm in the process of building the sign up functionality. My problem is when I try to access the localhost:3000/user/profile link I get this error message:
Failed to lookup view "/user/profile" in views directory
"/Users/vynguyen/shopping-cart/views
Error: Failed to lookup view "/user/profile" in views directory "/Users/vynguyen/shopping-cart/views"
at EventEmitter.render (/Users/vynguyen/shopping-cart/node_modules/express/lib/application.js:579:17)
at ServerResponse.render (/Users/vynguyen/shopping-cart/node_modules/express/lib/response.js:960:7)
at /Users/vynguyen/shopping-cart/routes/index.js:34:6
at Layer.handle [as handle_request] (/Users/vynguyen/shopping-cart/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/vynguyen/shopping-cart/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/Users/vynguyen/shopping-cart/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/vynguyen/shopping-cart/node_modules/express/lib/router/layer.js:95:5)
at /Users/vynguyen/shopping-cart/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/Users/vynguyen/shopping-cart/node_modules/express/lib/router/index.js:330:12)
at next (/Users/vynguyen/shopping-cart/node_modules/express/lib/router/index.js:271:10)
at csrf (/Users/vynguyen/shopping-cart/node_modules/csurf/index.js:117:5)
at Layer.handle [as handle_request] (/Users/vynguyen/shopping-cart/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/Users/vynguyen/shopping-cart/node_modules/express/lib/router/index.js:312:13)
at /Users/vynguyen/shopping-cart/node_modules/express/lib/router/index.js:280:7
at Function.process_params (/Users/vynguyen/shopping-cart/node_modules/express/lib/router/index.js:330:12)
at next (/Users/vynguyen/shopping-cart/node_modules/express/lib/router/index.js:271:10
)
The profile.hbs file is located in the right folder, but for some reason the server won't pull it up.
Here's the whole file structure:
enter image description here
Here's my index.js file:
var express = require('express');
var router = express.Router();
var csrf = require('csurf');
var passport = require('passport');
var Product = require('../models/product');
var csrfProtection = csrf();
router.use(csrfProtection);
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find(function(err, docs) {
var productChunks = [];
var chunkSize = 3;
for (var i = 0; i < docs.length; i += chunkSize) {
productChunks.push(docs.slice(i, i + chunkSize));
}
res.render('shop/index', { title: 'Shopping Cart', products: productChunks });
});
});
router.get('/user/signup', function(req, res, next) {
res.render('user/signup', {csrfToken: req.csrfToken()});
});
router.post('/user/signup', passport.authenticate('local.signup', {
successRedirect: '/user/profile',
failureRedirect: '/user/signup',
failureFlash: true
}));
router.get('/user/profile', function(req, res, next){
res.render('/user/profile');
});
module.exports = router;
Here's my app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressHbs = require('express-handlebars');
var mongoose = require('mongoose');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var routes = require('./routes/index');
var userRoutes = require('./routes/user');
var app = express();
mongoose.connect('localhost:27017/shopping');
require('./config/passport');
// view engine setup
app.set('views', __dirname+'/views');
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: 'mysupersecret', resave: false, saveUninitialized: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use('/user', userRoutes);
app.use('/', routes);
// 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 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;
When the view file path is resolved, the view path with leading slash will resolve to root directory and so the error. You need to resolve the view file relative to your views directory. Using user/profile or ./user/profile in res.render method would resolve the view file correctly.
correct code:
res.render('user/profile') or res.render('./user/profile')

404 Error in Node Application

Not Found
404
Error: Not Found
at c:\Users\wf\WebstormProjects\nodeExpress\app.js:33:13
at Layer.handle [as handle_request] (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:312:13)
at c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:280:7
at Function.process_params (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:330:12)
at next (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:271:10)
at c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:618:15
at next (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:256:14)
at Function.handle (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:176:3)
at router (c:\Users\wf\WebstormProjects\nodeExpress\node_modules\express\lib\router\index.js:46:12)
router code:
//about.js
var express = require('express');
var router = express.Router();
router.get('/about', function(req, res, next) {
console.log("/about route");
res.render('about', { title:'About',name:'Praveen' });
});
module.exports = router;
//app.js code
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var about = require('./routes/about');
//var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
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')));
app.use('/', routes);
app.use('/about', about);
//app.use('/users', users);
// 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;
enter code here
I'm getting above error if I try to access different route in my node application. Please help
The issue here is that the route in the about file is actually being resolved as /about/about. If you try open that URL it should work fine.
This is because in app.js, you say 'forward all requests that start with /about to about.js', so in about.js all routes already start with /about: app.use('/about', about);
To fix this, simply update the route in about.js to:
router.get('/', function(req, res, next) {

Categories

Resources