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);
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 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
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'm creating a MEAN Stack application where angular has setup in /client folder. I want that when I run npm start command in /client folder it should render index.html file from /views folder, what I'm doing wrong getting this error
Cannot GET /
Folder structure is as follows.
meanApp
----- client (angluar2 setup here but doesn't have an index.html file)
---------- app
----- views
----------index.html
----- routes
----- server.js
Codes in server.js
var express = require("express");
var path = require("path");
var bodyParser = require("body-parser");
var index = require('./routes/index');
var tasks = require("./routes/tasks");
var app = express();
//View engines
app.set("views", path.join(__dirname,'views'));
app.set("view engine", 'ejs');
app.engine("html", require("ejs").renderFile);
//Set static folder
app.use(express.static(path.join(__dirname,'client')));
// Body parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/', index);
app.use('/index', index);
app.use('/api', tasks);
//listen
app.listen(3000, function(){
console.log("Server listing # 3000");
});
Here you need to define route for express server like :
app.set('appPath', 'client'); //this is a folder where your index.html is
app.route('/*')
.get(function(req, res) {
res.sendfile(app.get('appPath') + '/index.html');
});
This will cause every call in broweser to render index file.
const http = require('http');
fs = require('fs');
var express = require('express');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var app = express();
app.set('appPath', 'views');
app.use(express.static(__dirname + '/views'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(expressValidator());
app.use('/*', function(req, res, next) {
res.sendfile(app.get('appPath') + '/index.html');
});
http.createServer(app).listen(3001, function() {
console.log(`Express server listening on port 3001`);
});
exports = module.exports = app;
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');