Cannot GET /index in nodejs - javascript

I have written a server named "app.js" which display many pages of my web site.
var http=require("http");
var express = require('express');
var app = express();
var server = http.createServer(app);
var ejs = require('ejs');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
// routes
var route = require('./route');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
server.listen(3000,function(){
console.log("server listen at localhost:3000");});
app.get('/', route.index);
route.js:
var index = function(req, res, next) {
if(!req.isAuthenticated()) {
res.redirect('/index');
} else {
var user = req.user;
if(user !== undefined) {
user = user.toJSON();
}
res.render('menu', {title: 'Home', user: user});
}
};
module.exports.index = index;
The folder of project:
/interface
/views
index.ejs
app.js
route.js
How can I fix it ? what is the mistake in my program?

Your app.get is unreachable after server.listen.
Place it before:
app.js:
var http=require("http");
var express = require('express');
var app = express();
var server = http.createServer(app);
var ejs = require('ejs');
var path = require('path');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
// routes
var route = require('./route');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// here:
app.get('/', route.index);
server.listen(3000,function(){
console.log("server listen at localhost:3000");});
// app.get('/', route.index); <= not here
When not authenticated, redirection is not what you want, but:
route.js:
// res.redirect('/index');
res.render('index');

Related

How to pass data "controller" instead of "app.js" in Nodejs

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);
});

Problem in rendering ejs template with Express

I am using Node.js together with Express and EJS.
Below is my code:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var publicPath = path.resolve(__dirname, 'public');
app.use(express.static(publicPath));
//app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/form_get.html', (req, res) => {
res.sendFile(__dirname + "/" + "form_get.html")
})
app.get('/process_get', (req, res) => {
console.log(req.query.first_name);
res.render(path.join(__dirname+'/views/thankyou.ejs'), { name: req.query.first_name});
})
var server = app.listen(3000, () => {
var host = server.address().address;
var port = server.address().port;
console.log(`Example app listening at ${host}:${port}`);
})
My folder structure is below:
mysql (folder)
node_modules (folder)
app4.js (file)
package.json (file)
public (folder, it contains form_get.html)
views (folder, it contains thankyou.ejs)
The problem is the failing to look up thankyou.ejs into the views folder.
I get the following error message:
Error: Failed to lookup view "thankyou.ejs" in views directory
".../mysql/views"
What can be the problem?
When You use app.set('view engine', 'ejs'); It is important to note that res.render() will look in a views folder for the view.
In this case
I mirrored Your project and it works fine with couple tiny changes...
Project Folder and file structure.
app.js
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var app = express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var publicPath = path.resolve(__dirname, "public");
app.use(express.static(publicPath));
app.set("view engine", "ejs");
app.get("/form_get", (req, res) => {
res.sendFile(__dirname + "/" + "form_get.html");
});
app.get("/process_get", (req, res) => {
res.render("thankyou");
});
var server = app.listen(3000, () => {
var host = server.address().address;
var port = server.address().port;
console.log(`Example app listening at ${host}:http://localhost:${port}`);
});
Output:
http://localhost:3000/process_get (thankyou.ejs) file.
Output:
http://localhost:3000/form_get (form_get.html) file

PassportJS nodejs request https

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;

Expressjs Static files not working

My controller
exports.index = function(req, res){
var info = {title: 'Index'};
res.render('index' , info);
};
exports.about = function(req, res){
var info = {title: 'about'};
res.render('about' , info);
};
exports.post = function(req, res){
var info = {title: 'Post'};
res.render('post' , info);
};
My routes.
var controller = require('../controllers/controller');
var router = require('express').Router();
router.route('/').get(controller.index)
router.route('/posts/:slug').get(controller.post)
router.route('/about').get(controller.about);
module.exports = router;
Server.js
var express = require('express');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var router = require(__dirname + '/routes/router');
var app = express();
app.set('views', __dirname + '/views');
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
app.use('/', router);
app.use(express.static(__dirname + '/public'));
app.listen(port);
Problem
When I got to http://localhost:8090/ or http://localhost:8090/about my static files work.
But if I visit any of the posts for example http://localhost:8090/posts/lorem-ipsum I get GET error in browser console. ( tried to server file from path http://localhost:8090/posts/css/style.css )
You have to serve static files first and then your routes, just switch line like this :
app.use(express.static(__dirname + '/public'));
app.use('/', router);

How can I mount MVC nodejs + express

I have a nodejs + express project. I want to mount controller and view, but I dont know how.
In my app.js I have var stats = require('./controllers/stats'); and app.use(stats);
My folder controllers: stats/index.js and my views: stats/index.jade.
when I try to access localhost:1200/stats --> Cannot GET /stats
Are routes needed?
I use express"3.2.6"
My app.js
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
//modulos
**var stats = require('./controllers/stats');**
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
//rutas
**app.use(stats);**
var server = app.listen(1200);
console.log('Express server listening on port 1200');
In my controller
var express = require('express');
var app = module.exports = express();
app.set('views', __dirname + '/views');
app.get('/views/stats', function(request, response) {
response.render('index', {
title: 'Estamos en el controlador stats'
});
});
In my view
extends layout
block content
h1= title
p Welcome to #{title}
p esta es la vista del controlador Stats
Here's the complete solution. Since this is a valid question I faced long ago, I give you the whole code. But whether to understand it or not is left to you.
In app.js
var config = require('./config/config.js');
var express = require('express');
var app = express();
config.setConfig(app, express);
if (config.requestMethod == 'HTTPS') {
var request = require('https');
var options = [config.httpsOptions, app];
} else if(config.requestMethod == 'HTTP') {
var request = require('http');
var options = [app];
}
require('./config/db.js');
var server = request.createServer.apply(this, options).listen(app.get('port'), function() {
console.log("Server started");
});
require('./route/router')(app);
In /config/config.js
var fs = require('fs');
module.exports = {
port: 8443,
mode: 'development',
requestMethod: 'HTTP',
httpsOptions: {
key: fs.readFileSync('/etc/apache2/ssl/server.key'),
cert: fs.readFileSync('/etc/apache2/ssl/server.crt'),
requestCert: false,
rejectUnauthorized: false
},
setConfig: function(app, express) {
app.set('port', process.env.PORT || module.exports.port);
app.set('view engine', 'jade');
app.use(express.favicon());
//app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
}
};
If it is HTTP only, you can remove HTTPS related options.
in /config/db.js
var mongo = require('mongoskin');
var MONGODB_HOST = "localhost";
var MONGODB_PORT = "27017";
var MONGODB_DATABSE = "dbname";
var MONGODB_USER_RW_NAME = "dbuser";
var MONGODB_USER_RW_PASS = "admin";
var db = mongo.db('mongodb://'+MONGODB_USER_RW_NAME+':'+MONGODB_USER_RW_PASS+'#'+MONGODB_HOST+':'+MONGODB_PORT+'/'+MONGODB_DATABSE, {safe: false});
var Tracking = require('../model/tracking.js');
GLOBAL.db = db;
GLOBAL.HOST = 'localhost';
GLOBAL.HEADER_MATCH = /localhost/i;
GLOBAL.ROOT_PATH = '/site/index.php/';
GLOBAL.Tracking = Tracking.construct(db);
Tracking is a custom model I wrote. You will see the code later.
In /route/router.js
router = function(app) {
var routes = {
'POST /test/link': 'testController.test'
};
var loadedControllers = {};
for(var i in routes) {
var requestMethod = i.split(' ')[0].toLowerCase();
var routeURL = i.split(' ')[1];
var controller = routes[i].split('.')[0];
var method = routes[i].split('.')[1];
if (loadedControllers[controller]) {
var loadControl = loadedControllers[controller];
} else {
var loadControl = require('../controller/' + controller);
loadedControllers[controller] = loadControl;
}
app[requestMethod](routeURL, loadControl[method]);
}
};
module.exports = router;
As and when you add a new URL, or API, you need to add one entry in routes object linking URL to a controller.
In /controller/testController.js,
exports.test = function(req, res) {
//Your code
};
In /model/Tracking/js,
exports.construct = function(db) {
var _Tracking = function(data) {
this.info = {
_id: data && data._id || null,
value: data.value || 0
};
_Tracking.test = function(id, cb) {
//your code involving db
cb(); //Send parameters to callback if necessary
//Call this function from controller directly using Tracking.test
};
return _Tracking;
};
That's it. You can build on top of this.
First of all I need three folders in the root of my app.
models
views
controllers
Now on to the app.js
var express = require('express');
,http = require('http');
,path = require('path');
,app = express();
,fs = require('fs');
// database connection
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydb');
// some environment variables
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// dynamically include routes (Controller)
fs.readdirSync('./controllers').forEach(function (file) {
if(file.substr(-3) == '.js') {
route = require('./controllers/' + file);
route.controller(app);
}
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Here is an example that I place in controllers/users.js
var mongoose = require('mongoose')
var Video = require('../models/user');
module.exports.controller = function(app) {
/**
* a home page route
*/
app.get('/signup', function(req, res) {
// any logic goes here
res.render('users/signup')
});
/**
* About page route
*/
app.get('/login', function(req, res) {
// any logic goes here
res.render('users/login')
});
}
res.render('users/signup') which results in the view being loaded from views/users/signup.jade in this app.
Finally, for reference, here is what the model in models/user.js may look like:
Var mongoose = require('mongoose')
,Schema = mongoose.Schema
userSchema = new Schema( {
username: String,
password: String
}),
User = mongoose.model('user', userSchema);
module.exports = User;

Categories