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);
});
Related
I am getting an error "indexRouter is not defined while I am trying to execute the following code. I tried removing the line but again there are other errors. Can anyone tell me why we are using this common variable router for both index.js and user.js?
This is my app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var dishRouter = require('./routes/dishRouter');
const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
const Dishes = require('./models/dishes');
const url = 'mongodb://localhost:27017/conFusion';
const connect = mongoose.connect(url,{
useMongoClient : true
});
connect.then((db) => {
console.log('Connected correctly to the server');
},(err) => {console.log(err);});
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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('/index',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;
This is my 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;
This is my users.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = router;
You are using wrong variable.
var index = require('./routes/index');
var users = require('./routes/users');
app.use('/index',indexRouter); // it would be index
app.use('/users',usersRouter); // it would be users
Change from indexRouter to index and userRouter to users.
After inserting ssl in my application nodejs the passportjs used for authentication layer informs that the user is not authenticated in the application after an AJAX POST is performed and the page undergoes a window.location.replace().
I have already looked at the documentation and found no reference to the problem, localhost using hpp I do not have this problem.
Would anyone help?
app.js
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var path = require('path');
var fileUpload = require('express-fileupload');
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync(path.join("key.pem")),
cert: fs.readFileSync(path.join("cert.pem"))
};
var app = express();
var expressValidator = require('express-validator');
var passport = require('passport');
var flash = require('connect-flash');
// - Cria rotas
var routes = require('./routes/index');
var usuarios = require('./routes/usuario');
var motorista = require('./routes/motorista');
var login = require('./routes/login');
var aluno = require('./routes/aluno');
var contrato = require('./routes/contrato');
var boleto = require('./routes/boleto');
var pessoa = require('./routes/pessoa');
require('./security/autenticacao')(passport);
app.use(logger('dev'));
app.use(expressValidator());
app.use(cookieParser());
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(session({
secret: 'reis&turlwaysrunning',
resave: true,
saveUninitialized: true
} ));
app.use(logErrors);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function (req, res, next) {
res.locals.login = req.user;
next();
});
app.use(fileUpload());
// Atriui rotas
app.use('/home', routes);
app.use('/usuarios', usuarios);
app.use('/alunos', aluno);
app.use('/motoristas', motorista);
app.use('/contratos', contrato);
app.use('/login', login);
app.use('/boletos', boleto);
app.use('/pessoas', pessoa);
https.createServer(httpsOptions, app).listen(8080);
app.set('port', process.env.PORT || 21108);
app.listen(app.get('port'));
function logErrors (err, req, res, next) {
console.error('Troxa: ' + err.stack)
next(err)
}
module.exports = app;
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!
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
Error: "node_modules/express/lib/router/index.js:458 Router.use() requires a middleware function but got a Object at Function.use"
Code:
const express = require('express');
const bodyParser = require('body-parser');
const mustacheExpress = require('mustache-express');
const pgp = require('pg-promise');
const port = process.env.PORT || 3000;
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.engine('html', mustacheExpress());
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
const students = require('./controllers/students.js');
const houses = require('./controllers/houses.js');
app.use('/houses', houses);
app.use('/students', students);
app.get('/', (req, res) => res.render('home/index'));
app.listen(port, () => { console.log("Server started on " + port); });
module.exports = router;
controllers/students.js:
This is the first file which is linked to the index.js
const router = require('express').Router();
const Students = require('../models/students.js');
router.get('/',
Students.findAll, (req, res) => {
res.render('students/index', {studentsData: res.locals.allStudentsData})
});
router.get('/:id', Students.findById, (req, res) => {
res.render('students/show', res.locals.showStudent)
});
module.exports = router;
controllers/houses.js:
This is the second file which is linked to the index.js
const router = require('express').Router();
const Houses = require('../models/houses.js');
router.get('/',
Houses.findAll, (req, res) => {
res.render('houses/index', {housesData: res.locals.allHousesData})
});
router.get('/:id', Houses.findById, (req, res) => {
res.render('houses/show', res.locals.showHouse)
});
module.exports = router;