I have a simple nodejs app with some users. I want to load a specific user profile using a URL localhost/users/(username) but I'm getting this error when I try to load the URL:
Cannot GET /users/test
Here's my user.js routes file for the user page:
var express = require('express');
var router = express.Router();
var User = require('../models/user');
// GET user by username
router.get('/users/:username', function(req, res) {
var username = req.params.username;
res.send(req.params);
res.render('user');
});
module.exports = router;
I have a user.handlebars file in my views folder so it should load the file. What am I missing in my routes file? Any help would be greatly appreciated. Thanks!!
EDIT: app.js:
console.log('Starting app.js');
const fs = require('fs');
const _ = require('lodash');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const exphbs = require('express-handlebars');
const expressValidator = require('express-validator');
const flash = require('connect-flash');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('mongodb');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/tipcup');
var db = mongoose.connection;
const routes = require('./routes/index');
const users = require('./routes/users');
const user = require('./routes/user');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine', 'handlebars');
// BodyParser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport Init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator ({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use('/users/:username', user);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
Render function renders a view and sends the rendered HTML string to the client.Take a look at documentation.
But what you are trying to archive is to send data first and then render and send again. So, just delete the line with send.
router.get('/users/:username', function(req, res) {
var username = req.params.username;
res.render('user');
});
And, please, edit your question by adding your code with middleware and add your error.
Update
Take a look at the way how you define your routes for users.
You have to remove /users from defining route in users.js file
Related
I am working on Nodejs(Express.js),I am sending Form data to controller but not working for me,I am getting error "TypeError: Cannot read property 'name' of undefined in Nodejs", But Main problem is my code is working/getting data in "app.js" but i want to get data in "userController" because i want to use MVC strtucre,Here is my root.js
var express=require('express');
var router= express.Router();
var controllers= require('../controllers');
router.get('/', controllers.homeController.index);
router.get('/signup', controllers.userController.signup);
router.post('/signup', controllers.userController.save);
router.get('/login', controllers.userController.login);
router.get('/dash', controllers.userController.dash);
module.exports = router;
Here is my userController.js file
userController.save = function (req, res, next) {
var name = req.body.name;
console.log(name);
}
Here is my app.js, How can i get data in "userController" instead of "app.js",Thank you in advance.
const express = require('express');
const mysql = require('mysql');
const expressValidator = require('express-validator');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', routes);
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(__dirname + '/public'));
app.use(cookieParser('keyboard cat'));
const PORT = 4000
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log("App started on PORT", PORT);
});
I have reorganized your codes. Please make sure your filte path declaration is correct.
var express=require('express');
var router = express.Router();
var controllers= require('../controllers/userController'); // if userController.js in controller folder.
router.get('/', controllers.homeController_index);
router.get('/signup', controllers.userController_signup);
router.post('/signup', controllers.userController_save);
router.get('/login', controllers.userController_login);
router.get('/dash', controllers.userController_dash);
module.exports = router;
userController.js
const userController_save = function (req, res, next) {
var name = req.body.name;
console.log(name);
}
app.js
const express = require('express');
const mysql = require('mysql');
const expressValidator = require('express-validator');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const flash = require('connect-flash');
const path = require("path");
const app = express();
const routes = require('./routes/root'); // If your root.js inside a routes folder
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(__dirname + '/public'));
app.use(cookieParser('keyboard cat'));
app.use('/', routes);
const PORT = 4000
app.listen(PORT, function (err) {
if (err) console.log(err);
console.log("App started on PORT", PORT);
});
I am new to Node (frameworks in general), and I have some problems that I cannot find answers to after searching for days.
When I click on a specific client, I now get redirected to 'create-survey' which is correct. But after that I want the url to be something like '/create-survey/companyx' and get the data with me from that specific client that I clicked on in the new view '/create-survey/companyx'.
index.js:
router.get('/create-survey/:company', ensureAuthenticated, function(req, res) {
Client.find({}, {}, function (err, docs){
res.render('create-survey/:company', {"client" : docs});
})
});
app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
// Routes
var routes = require('./routes/index');
var users = require('./routes/users');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Connect to Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
app.use(express.static('public'));
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
and the last, create-survey.handlebars
<h2 class="page-header">Create a survey for {{client.company}}</h2>
<tr>
<strong>Company</strong>
<td><p>{{client.company}}</p></td>
<strong>Contact person</strong>
<td><p>{{client.contact}}</p></td>
<strong>Email adress</strong>
<td><p>{{client.email}}</p></td>
</div>
As I said, I'm a beginner that still is trying to learn, so come with all kind of feedback and help and I'll be happy!
Ive been recently learning how to use node.js to create a backend login system with passport. Im running it locally with a mongoDB. The url I use to access it is http://localhost:3000. Now when I go to that url instead of displaying my index.handlebars page it routes me to http://localhost:3000/users/login. Im wondering why this is? Ill provide a few files let me know if there is anything else you may need.
Not sure what else you would need, but I have looked through my code hundreds of times and cant find out why. My routes seem fine, my static folder seems fine. Im just lost. Any help would be appreciated.
My directory looks like this,
loginapp-master
-models
-users.js
-node_modules
-public
-css
-fonts
-js
-routes
-index.js
-users.js
-views
-layouts
-layout.handlebars
-index.handlebars
-login.handlebars
-register.handlebars
.gitignore
app.js
package-lock.json
package.json
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
// Init App
var app = express();
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view engine', 'handlebars');
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Passport init
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', routes);
app.use('/users', users);
// Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});
I am new in node and express and i am making logapp when i run node app.js it show an error app.use() requires a middleware function i install all the npm which was required to run the project is there any way to solve this problem i really cant understand what am i doing wrong. any help thanks in advance.this is my app.js code
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validators');
var flash = require('connect-flash');
var session = require('express-sessions');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', exphbs({defaultLayout:'layout'}));
app.set('view', 'handlebars');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'secret',
saveUninitialized:true,
resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(flash());
app.use(function(req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
})
app.use('/', routes);
app.use('/users', users);
app.set('port', (process.env.PORT || 3000 ));
app.listen(app.get('port'), function(){
console.log('Server started on Port ' + app.get('port'));
})
I think you are using wrong npm module. Instead of
var expressValidator = require('express-validators');
use
var expressValidator = require('express-validator');
a question which was often discussed(error message: Router.use() requires middleware function but got a Object) , but the answers in the other feeds does'nt work. e.g.
app.use(app.router);
routes.initialize(app);
This code brings the message:
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x
migration guide for details on how to update your app.');
^
Error: 'app.router' is deprecated!
Please see the 3.x to 4.x migration guide for details on how to update your app.
I hope there will be a better idea.
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
//mongoose.connect('mongodb://localhost/dbname');
//var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
//Init App
var app = express();
//View Engine
app.set('views',path.join(__dirname,'views'));
app.engine('handlebars', exphbs({defaultLayout: 'layout'}));
app.set('view engine','handlebars');
//BodyParser Middleware
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(urlencodedParser);
app.use(cookieParser());
//Set Static Folder
app.use(express.static(path.join(__dirname,'public')));
//Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//Passprt init
app.use(passport.initialize());
app.use(passport.session());
//Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
//Connect Flash
app.use(flash());
//Global Vars
app.use(function(req,res, next) {
res.locals.success_msg = req.flash('succes_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
//Set Routes
app.use('/', require('./routes/index'));
app.use('/users', require('./routes/users'));
// Set Port
app.set('port',(process.env.PORT || 3000));
//Start Server
app.listen(app.get('port'), function(){
console.log('Server started on port '+app.get('port'));
});