Express only works on port 3000 - node.js

My app only works on port 3000.
If i change port to anything else, it'll work but when a page loads it occurs this error.
abc is not defined
at eval (eval at compile (C:\Users\ASUS\node_modules\ejs\lib\ejs.js:549:12), :22:26)
at returnedFn (C:\Users\ASUS\node_modules\ejs\lib\ejs.js:580:17)
at tryHandleCache (C:\Users\ASUS\node_modules\ejs\lib\ejs.js:223:34)
at View.exports.renderFile [as engine] (C:\Users\ASUS\node_modules\ejs\lib\ejs.js:437:10)
at View.render (C:\Users\ASUS\node_modules\express\lib\view.js:128:8)
at tryRender (C:\Users\ASUS\node_modules\express\lib\application.js:640:10)
at EventEmitter.render (C:\Users\ASUS\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\ASUS\node_modules\express\lib\response.js:971:7)
at C:\Users\ASUS\Desktop\nodeweb\controllers\index.js:21:6
at Layer.handle [as handle_request] (C:\Users\ASUS\node_modules\express\lib\router\layer.js:95:5)
abc is a variable i'm using in index.ejs, defined in router.
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
res.render('index', {abc: 23})
});
module.exports = router;
I'm starting my server with node app command
var app = express();
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'));
app.use(require('./controllers'))
app.listen(8080, function() {
console.log('Listening on port 8080...')
})
UPDATE
I think i found the problem
It works when i use
app.use('/', function(req, res) {
res.render('index', {tit:[1,2,3,4,5]});
})
instead of
app.use(require('./controllers'))
But why?
UPDATE
It just fixed itself, it works normally now and i don't know why. That sucks.

You could try hard coding the port:
app.set("port", process.env.PORT || 3000);
Or this:
$ PORT=8080 node app.js
Also if you are not on Windows, and want to use ports bellow 1024 try this first:
sudo PORT=80 node app.js

If you want to place the route handlers in a separate file, then you can, just no need to call the file with app.use(...).
Instead, you can just do:
require('./controllers');
It has nothing to do with the abc variable.

It is because , I think controller is not properly imported . If you write like this I think, it will work fine
var router = require('express').Router();
router.get('/', function(req, res) {
res.render('index', {abc: 23})
});
module.exports = router;
var app = express();
var route = require('./router')
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'));
app.use('/',route);
app.listen(8080, function() {
console.log('Listening on port 8080...')
})
Here be careful when you define require('./router') in var route = require('./router') ,because it is relative so it totally depends on your folder structure.

Related

Failed to lookup view "index" in views directory | Express | HBS instead of handlebars.js

view-engine
I have installed hbs instead of handlebar for dynamic templating, and now I'm stuck at this problem.
Error: Failed to lookup view "index" in views directory "/home/trijay/Desktop/NodeJs/web-server/src/views"
at Function.render (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/application.js:580:17)
at ServerResponse.render (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/response.js:1008:7)
at app.get (/home/trijay/Desktop/NodeJs/web-server/src/app.js:14:9)
at Layer.handle [as handle_request] (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/layer.js:95:5)
at next (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/layer.js:95:5)
at /home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/index.js:335:12)
at next (/home/trijay/Desktop/NodeJs/web-server/node_modules/express/lib/router/index.js:275:10)
Below is my code for app.js and also I have installed the hbs, express library. Any help will be appreciated
//app.js
const express = require('express')
const path = require('path')
const publicPath = path.join(__dirname, '../public') //for accessing comeplete file
const app = express() //express being initialised
app.use(express.static(publicPath))
app.set('view engine', 'hbs') //use to set handle bars. we need to provide key value pair
app.get('', (req, res) => {
res.render('index') //need to provide the hbs file name which you will find in view
})
app.get('/weather', (req, res) => {
res.send({
latitude: -57.89,
longitude: 78.42,
location : 'New Delhi'
})
})
app.listen(3000, () => {
console.log('Server Started on port 3000')
})
Add a views directory to the engines options:
app.set('view engine', 'hbs')
app.set('views', path.join(__dirname, '../views'));
As you can see in the error message:
Error: Failed to lookup view "index" in views directory "/home/trijay/Desktop/NodeJs/web-server/src/views"
res.render('index') points somewhere in src directory.
I think you may forgot to setup the engine after defining it.
app.set('view engine', 'hbs');
app.engine( 'hbs', hbs( {
extname: 'hbs',
defaultView: 'index' //your default template
}));
Try this and let me know.

SyntaxError: Unexpected token ,while compiling ejs

I just started to learn Node JS. While rendering the ejs file, I got an Unexpected token error. Anyone help me out for this error. My code is below:
ERROR:
SyntaxError: Unexpected token { in C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\views\blogpost.ejs while compiling ejs
If the above error is not helpful, you may want to try EJS-Lint:
https://github.com/RyanZim/EJS-Lint
Or, if you meant to create an async function, pass async: true as an option.
at new Function (<anonymous>)
at Template.compile (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:633:12)
at Object.compile (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:392:16)
at handleCache (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:215:18)
at tryHandleCache (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:254:16)
at View.exports.renderFile [as engine] (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\ejs\lib\ejs.js:485:10)
at View.render (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\application.js:640:10)
at Function.render (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\application.js:592:3)
at ServerResponse.render (C:\Users\Ghulam Abbas\Desktop\Node\Conditionals\node_modules\express\lib\response.js:1012:7)
app.js
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('Blog Homepage.');
});
app.get('/posts', function(req, res) {
res.render('blogpost.ejs', {posts : "posts"});
});
app.listen(3000, function() {
console.log("Server is started.");
});
blogpost.ejs
<h1>Blog <%= posts %> </h1>
Thanks in advance.
I just update your code, seem you're forgot set view engine
var express = require('express');
var app = express();
var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.send('Blog Homepage.');
});
app.get('/posts', function(req, res) {
res.render('blogpost.ejs', {posts : "posts"});
});
app.listen(3000, function() {
console.log("Server is started.");
});
Please make sure you run npm i ejs.
And you may need store all your view files in a folder for more clearly folder struct. In this code, please move your blogpost.ejs to views folder. Hope this helpfull
const express = require('express');
const path = require('path');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', (req, res)=>{
res.render('homepage');
});
app.get('blog', (req, res)=>{
let post = req.query.post;
res.render('blog', {post: post});
});
let port = 4444;
app.listen(port, ()=>{
console.log(`server has started on port: ${port}`);
});

Express router and routes Node.js

I get this error when I try to route my
My code
'use strict';
const express = require('express');
const app = express ();
const chatCat = require ('./app');
app.set('port', process.env.PORT || 3000);
app.use(express.static('public'));
app.set('view engine', 'ejs');
app.use('/', chatCat.router);
app.listen(app.get('port'), () => {
console.log('running on port:', app.get('port'));
});
Error
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
I tried routing but it keeps giving me errors from my express.js.
Try this code:
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.static('public'));
app.set('view engine', 'ejs');
var chatCat = require('./app');
app.use('/',chatCat);
app.listen(port,function(){
console.log("Server is running on port: "+port);
});
Try creating app with this https://expressjs.com/en/starter/generator.html it will create nice structure for your project. As for your error - it needs to be express middleware function. You can't import router from your app.js as it don`t have such property. If you want to have route described here use:
app.method('/yourRoute', function(req, res, next){
//your middleware code
});
also change this:
app.listen(app.get('port'), () => {
console.log('running on port:', app.get('port'));
});
to this:
app.listen(3000);
And you can change 3000 to any unused port you want

Failed to lookup view in views directory by express.js and path

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.

Failed to lookup view

Hi I'm trying to work with Express 3 using handlebars. But I am unable to "lookup the view" I am stuck with this error.
Error: Failed to lookup view "500" in views directory
"d:\projects\meadowlark\site\views" at EventEmitter.app.render
(d:\projects\meadowlark\site\node_modules\express\lib\application.js:519:17)
at ServerResponse.res.render
(d:\projects\meadowlark\site\node_modules\express\lib\response.js:904:7)
at d:\projects\meadowlark\site\meadowlark.js:29:7 at
Layer.handle_error
(d:\projects\meadowlark\site\node_modules\express\lib\router\layer.js:58:5)
at trim_prefix
(d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:269:13)
at
d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:238:9
at Function.proto.process_params
(d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:313:12)
at
d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:229:12
at Function.match_layer
(d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:296:3)
at next
(d:\projects\meadowlark\site\node_modules\express\lib\router\index.js:190:10)
Its really strange for me. Can anyone explain this issue to me how can I solve it?
My js code is as follows:
var express = require('express');
var app = express();
// set up handlebars view engine
var handlebars = require('express3-handlebars')
.create({ defaultLayout:'main' });
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('port',process.env.port || 3000);
app.get('/', function(req, res) {
res.render('home');
});
app.get('/about', function(req, res) {
res.render('about');
});
// 404 catch-all handler (middleware)
app.use(function(req, res, next){
res.status(404);
res.render('404');
});
// 500 error handler (middleware)
app.use(function(err, req, res, next){
console.error(err.stack);
res.status(500);
res.render('500');
});
app.listen(app.get('port'),function(){
console.log('Express started on http://localhost: '+ app.get('port') + " Press CTRL+C to terminate.");
});
I think I know what the issue here is, remember this setup of app.js from an O'Reilly book ("Web Development with Node & Express").
Here's what the author fails to clarify:
If you have your .handlebars template files in views/layouts/, structure your view engine setup like this:
var path = require('path');
var express = require('express');
var handlebars = require('express-handlebars'); // 'express3-handlebars' has been deprecated
var app = express();
// Set up handlebars view engine
app.set('views', path.join(__dirname, 'views/layouts/'));
app.engine('handlebars', handlebars({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
Note that you will need the var path = require('path'); in order to set 'views' to the filepath views/layouts/.
If you read the error, it clearly tells you that you are missing a 500 view template in your template directory. I'm not sure what your directory structure you have, but place a 500.handlebars file in the same directory the 404.handlebars file is. Should be somewhere in the views/ or views/layouts directory.
Make sure that your files: home.handlebars, about.handlebars, 404.handlebars, 500.handlebars and main.handlebars don't have hidden extensions. Like this: home.handlebars.html, about.handlebars.html, 404.handlebars.html, 500.handlebars.html, and main.handlebars.html.
If they do, removing those extensions and using only the .handlebars extension should resolve the issue.

Resources