I'm new to node and having difficulty to get a simple express-handlebar to render a static html page:
require('./config/config');
const path = require('path');
const http = require('http');
const _ = require('lodash');
const express = require('express');
const bodyParser = require('body-parser');
const {ObjectID} = require('mongodb');
const socketIO = require('socket.io');
const exphbs = require('express-handlebars');
var {mongoose} = require('./db/mongoose');
var {Todo} = require('./models/todo');
var {User} = require('./models/user');
var {authenticate} = require('./middleware/authenticate');
var app = express();
var server = http.createServer(app);
var io =socketIO(server);
const port = process.env.PORT;
const publicPath = path.join(__dirname, './public');
app.use(bodyParser.json());
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', exphbs);
app.use(express.static(publicPath));
app.get('/', (req, res) => {
res.render('index');
});
Instead of index.html sitting in views folder, I get this error:
Error: Cannot find module 'function exphbs(config) {
return create(config).engine;
}'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at new View (/home/me/nodechatapp/node_modules/express/lib/view.js:81:14)
at Function.render (/home/me/nodechatapp/node_modules/express/lib/application.js:570:12)
at ServerResponse.render (/home/me/nodechatapp/node_modules/express/lib/response.js:1008:7)
at app.get (/home/me/nodechatapp/server.js:37:7)
at Layer.handle [as handle_request] (/home/me/nodechatapp/node_modules/express/lib/router/layer.js:95:5)
at next (/home/me/nodechatapp/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/me/nodechatapp/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/me/nodechatapp/node_modules/express/lib/router/layer.js:95:5)
at /home/me/nodechatapp/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/me/nodechatapp/node_modules/express/lib/router/index.js:335:12)
at next (/home/me/nodechatapp/node_modules/express/lib/router/index.js:275:10)
at SendStream.error (/home/me/nodechatapp/node_modules/serve-static/index.js:121:7)
What could be wrong here? How can I fix it?
I'm pretty sure you are missing the app.engine() call in your server set up. Based on the docs you need:
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
You already use app.set for the view engine, but I think you need to call the prior line.
Related
I have a problem to route views by node.js and express.js
The tree of my project is look like :
app/
app.js
views/
index.html
login.html
public/
css/
js/
I use express and path ; Here is my code to set paths:
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//forms
app.set('views', path.join(__dirname, 'views'));
//public
app.use(express.static(path.join(__dirname, 'public')));
And I am getting this error:
Error: Failed to lookup view "login.html" in views directory "/home/Project/V0.0.8_3/app/views"
at EventEmitter.render (/home/Project/V0.0.8_3/node_modules/express/lib/application.js:580:17)
at ServerResponse.render (/home/Project/V0.0.8_3/node_modules/express/lib/response.js:966:7)
at /home/Project/V0.0.8_3/app/routes/login.js:11:11
at Layer.handle [as handle_request] (/home/Project/V0.0.8_3/node_modules/express/lib/router/layer.js:95:5)
at next (/home/Project/V0.0.8_3/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/Project/V0.0.8_3/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/Project/V0.0.8_3/node_modules/express/lib/router/layer.js:95:5)
at /home/xvps/Tracker/V0.0.8_3/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/Project/V0.0.8_3/node_modules/express/lib/router/index.js:335:12)
at next (/home/Project/V0.0.8_3/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/home/Project/V0.0.8_3/node_modules/express/lib/router/index.js:174:3)
at router (/home/Project/V0.0.8_3/node_modules/express/lib/router/index.js:47:12)
at Layer.handle [as handle_request] (/home/Project/V0.0.8_3/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/Project/V0.0.8_3/node_modules/express/lib/router/index.js:317:13)
at /home/Project/V0.0.8_3/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/Project/V0.0.8_3/node_modules/express/lib/router/index.js:335:12)
and when I try to get a file from public directory I get this error:
Cannot GET /js/login.js
Actually I know different between local path and server path and I have read a lot of related questions have been asked in stack overflow but I cannot find what is my mistake.
UPDATE
And the routing code is here:
var router = express.Router();
require('./router')(app);
the router.js:
var routes = require('./routes/index');
var login = require('./routes/login');
module.exports = function (app) {
/* Index(main) route */
app.use('/', routes);
app.use('/index', routes);
app.use('/index.html', routes);
app.use('/login', login);
app.use('/login.html', login);
app.use('/logout', logout);
};
at routes directory there are two js files; index.js and login.js
index.js:
var express = require('express');
var router = express.Router();
router.route('/')
// fetch all users
.get(function (req, res) {
console.log('get method');
if(req.session.logged) {
res.render('index.html');
}
else {
res.redirect('/login');
}
});
module.exports = router;
Which express version are you using?
Updated
In express 4 middlewares are built in external modules, so for static files in you case, you should use serve-static middleware:
Example code:
var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
app.use(serveStatic(path.join(__dirname, 'public')))
app.listen(3000)
Because I was beginner on coding by node.js and uploading on server I was running my code on server by npm, one of my friends helped me t find my problem. I must run the app by pm2 to get a live application.
I was also getting this error, but after getting some mental fatigue I am able to resolve this. Here is the solution that works fine for me.
Change this line of code app.set('views', path.join(__dirname, 'views')); to app.set('views', path.join(__dirname, '../views')); this.
I'm doing a web page with the express generator, I have three pages in jade, but when I want to go from one to another it shows me this mistake:
Error: Not Found
at app.use.res.render.message (F:\NodeJSPortable\Data\letstalksaku\app.js:39:13)
at Layer.handle [as handle_request] (F:\NodeJSPortable\Data\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (F:\NodeJSPortable\Data\node_modules\express\lib\router\index.js:312:13)
at F:\NodeJSPortable\Data\node_modules\express\lib\router\index.js:280:7
at Function.process_params (F:\NodeJSPortable\Data\node_modules\express\lib\router\index.js:330:12)
at next (F:\NodeJSPortable\Data\node_modules\express\lib\router\index.js:271:10)
at SendStream.error (F:\NodeJSPortable\Data\node_modules\express\node_modules\serve-static\index.js:120:7)
at SendStream.emit (events.js:95:17)
at SendStream.error (F:\NodeJSPortable\Data\node_modules\express\node_modules\send\index.js:245:17)
at SendStream.onStatError (F:\NodeJSPortable\Data\node_modules\express\node_modules\send\index.js:356:12)
This is the code from 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 fs = require('fs');
var https = require('https'),
http = require('http');
var routes = require('./routes/index');
var users = require('./routes/users');
var index2 = require('./routes/index2');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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')));
require('./routes')(app);
module.exports = app;
https.createServer({key: privateKey, cert: certificate}, app).listen(8000);
http.createServer(app).listen(8001);
console.log('running on https://localhost:8000 and http://localhost:8001');
My jade files just have this code
doctype html
html
head
body
a#Boton1(href='/index2') Crea tu sala
I just can't find the mistake, would you please help me
Looks like a simple task, but I can not find out the error in my code.
app.js
var http = require('http');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var routes = require('./routes')(app);
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.set('view engine', 'jade');
app.set('views', './views');
app.use(express.static('./public'));
app.listen(3000, function() {
console.log('hello');
console.log('express server listening on port:' + 3000);
});
index.jade
html
head
title Welcome
body
p Enter your name and email address to become a member.
form(action='/signup', method='post')
div
label Name
input(type='text', name='name')
div
label Email
input(type='text', name='email')
div
input(type='submit')
routes.js
module.exports = function(app) {
app.get('/', function(req, res) {
res.render('index');
});
app.post('/signup', function(req, res) {
console.log(req);
console.log(req.body);
var name = req.body.name;
var email = req.body.email;
console.log('Name: ' + name);
console.log('Email: ' + email);
res.json(req.body);
});
};
When I post the form I get the error:
TypeError: Cannot read property 'name' of undefined
at /Users/demas/temporary/express/1/routes.js:11:22
at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/demas/temporary/express/1/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch (/Users/demas/temporary/express/1/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
at /Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:277:22
at Function.process_params (/Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:330:12)
at next (/Users/demas/temporary/express/1/node_modules/express/lib/router/index.js:271:10)
at expressInit (/Users/demas/temporary/express/1/node_modules/express/lib/middleware/init.js:33:5)
at Layer.handle [as handle_request] (/Users/demas/temporary/express/1/node_modules/express/lib/router/layer.js:95:5)
In the console I can see the req.body is undefined. Why?
You need to do your configuration before you do the routing, so moving down this line :
var routes = require('./routes')(app);
Below this :
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
... should work.
I am trying to create a server for an app with a node JS server on AWS(not sure how relevant that is) and I am testing it with Postman. For some reason my hello world function, which is just a GET works perfectly but my POST to create a user keeps giving me this error:
TypeError: Cannot read property 'username' of undefined
at app.get.params.QueueUrl (/home/ec2-user/Outfitr/Server/index.js:40:29)
at Layer.handle [as handle_request] (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/layer.js:82:5)
at next (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/route.js:110:13)
at Route.dispatch (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/route.js:91:3)
at Layer.handle [as handle_request] (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/layer.js:82:5)
at /home/ec2-user/Outfitr/Server/node_modules/express/lib/router/index.js:267:22
at Function.proto.process_params (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/index.js:321:12)
at next (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/index.js:261:10)
at serveStatic (/home/ec2-user/Outfitr/Server/node_modules/express/node_modules/serve-static/index.js:59:14)
at Layer.handle [as handle_request] (/home/ec2-user/Outfitr/Server/node_modules/express/lib/router/layer.js:82:5)
Here is my code:
var express = require("express")
var app = express();
var gm = require("gm");
var fs = require("fs");
var async = require("async");
var s3 = new AWS.S3();
// set the region for the AWS API requests
AWS.config.region = 'us-west-2';
var DAO_QUEUE_URL = 'https://sqs.us-west-2.amazonaws.com/275333356355/DAO-Queue';
app.set('port', (process.env.PORT || 8080 ));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.send('Hello World (Finally)');
});
app.post('/create_user', function( request, response) {
process.stdout.write("WTF");
create_user( request.body.username, request.body.password, request.body.firstname, request.body.lastname, request.body.gender, request.body.latitude,
request.body.longitude, request.body.description, request.body.city,
request.body.state_province, request.body.country, request.body.email,
request.body.phone_number);
response.send('IT WORKED!');
});
function create_user( username, password, firstname, lastname, is_brand, gender,
description, city, state_province, country, birthday) {
messageBody = {"username":username, "password":password, "firstname": firstname,
"lastname":lastname, "is_brand":is_brand, "gender":gender, "city":city,
"state-province":state_province, "country":country, "birthday":birtyhday};
queueUrl = DAO_QUEUE_URL;
sendSQSMessage( JSON.stringify(messageBody),queueUrl);
}
What could be wrong?
Make sure that you are using the x-www-form-urlencoded tab in postman. I've fallen for that a few times.
Also, make sure you are using the body-parser package.
var express = require("express")
var app = express();
var gm = require("gm");
var fs = require("fs");
var async = require("async");
var bodyParser = require('body-parser');
var s3 = new AWS.S3();
// set the region for the AWS API requests
AWS.config.region = 'us-west-2';
var DAO_QUEUE_URL = 'https://sqs.us-west-2.amazonaws.com/275333356355/DAO-Queue';
// Add the middleware
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.set('port', (process.env.PORT || 8080 ));
app.use(express.static(__dirname + '/public'));
So I think that you are getting the error because there is no middleware setting up a req.body object for you, bodyParser should do the trick.
I am trying to make a app, in the app directory this is my app.js file. in the app.js I am requiring the router folder and exporting the Routes. But I am not able to render the index.jade using the Router instead i am getting error:
D:\Projects\socialApp\node_modules\express\lib\router\index.js:423
throw new TypeError(msg);
^
TypeError: Router.use() requires callback function but got a [object Undefined]
at D:\Projects\socialApp\node_modules\express\lib\router\index.js:423:13
at Array.forEach (native)
at Function.use (D:\Projects\socialApp\node_modules\express\lib\router\index
.js:419:13)
at D:\Projects\socialApp\node_modules\express\lib\application.js:178:21
at Array.forEach (native)
at Function.use (D:\Projects\socialApp\node_modules\express\lib\application.
js:175:7)
at Object.<anonymous> (D:\Projects\socialApp\app.js:22:6)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
D:\Projects\socialApp>
here is my app.js:
var express = require("express"),
passport = require("passport"),
passportLocal = require("passport-local"),
bodyParser = require("body-parser"),
cookieParser = require("cookie-parser"),
expressSession = require("express-session"),
jade = require("jade"),
mongoose = require("mongoose"),
routes = require('./routes'),
port = process.env.PORT || 3000,
app = express();
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));
app.use(passport.initialize());
var routes = require('./routes/index')(passport); //i am calling here
app.use('/', routes); // not getting index.jade on screen.
app.listen(port, function(){
console.log('Port Listing to ' + port + ":" + __dirname);
});
here is what in the router folder and in the index.js:
var express = require('express'),
router = express.Router();
module.exports = function(passport){
router.get('/', function(req,res){
res.render('index'); //i am not getting index.jade from view folder getting error
});
}
any one figure-out the issue please?
You need to return router; at the end of your module.exports function.