SyntaxError: Unexpected token ,while compiling ejs - node.js

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

Related

Error: Failed to lookup view "users/register" in views directory

My app can not find a page from the views directory. I think I've setup the configuration correctly and other files are working fine in views but this one is not working.
Error: Failed to lookup view "users/register" in views directory "D:\NODE PROJECTS\MyBlog\views"
at Function.render (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\application.js:580:17)
at ServerResponse.render (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\response.js:1017:7)
at file:///D:/NODE%20PROJECTS/MyBlog/src/routes/UserRouter.js:18:9
at Layer.handle [as handle_request] (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\router\layer.js:95:5)
at next (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\NODE PROJECTS\MyBlog\node_modules\express\lib\router\route.js:112:3)
This is my path setup
app.engine('ejs', engine)
app.set('view engine', 'ejs')
app.set('views', path.join(__dirname, '../templates/views'))
And a call from router
UserRoter.get('/register', (req, res)=>{
res.render('users/register', {title: 'Sign Up'})
})
And this is the structure of views directory
You have a bug in the third line of code, instead of:
app.set('views', path.join(__dirname, '../templates/views'))
Should be:
app.set('views', path.join(__dirname, '/templates/views'))
I mirrored your project (folder and file structure) and everything seems to be fine:-)
Folder & file structure :
app.js
const express = require("express");
const path = require("path");
const port = 3000;
const app = express();
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "/templates/views"));
app.get("/", (req, res) => {
res.render("index", { title: "Keep Calm and Do not stop coding!" });
});
app.get("/register", (req, res) => {
res.render("users/register", { title: "Sign Up" });
});
app.listen(port, () => {
console.log(`Server is listening at http://localhost:${port}`);
});
register.ejs
<title><%= title %></title>
<h1>Register page works fine!</h1>
output:
Tested with "ejs": "^3.1.6", "express": "^4.17.2", node 16.13.0

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.

Module not found error - NodeJS Express.JS

I'm trying to catch the post data from my form and when I'm done with processing I want it to render the index.html file again.
Although when I'm trying the code as displayed below, I get an error.
The error:
Error: Cannot find module 'html'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at new View (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/view.js:81:14)
at Function.render (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/application.js:570:12)
at ServerResponse.render (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/response.js:1008:7)
at /Applications/XAMPP/xamppfiles/htdocs/controlpanel/server.js:14:9
at Layer.handle [as handle_request] (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/router/layer.js:95:5)
at next (/Applications/XAMPP/xamppfiles/htdocs/controlpanel/node_modules/express/lib/router/route.js:137:13)
The code:
var express = require('express');
var session = require('express-session');
var app = express();
app.use('/public', express.static('public'));
app.use( express.static('public/html') );
app.post('/', function(req, res, next) {
console.log('start processing postdata...');
next()
});
app.all('/', function(req, res) {
res.render('html/index.html');
});
app.listen(2222);
Everything works fine for the GET method.
Only the POST request is causing this error.
What am I doing wrong?
Thanks in advance, Laurens
Here is the working code, you should use sendFile instead if render. Render is been used with views.
'use strict';
let express = require('express');
// let session = require('express-session');
let app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/public', express.static('public'));
app.use(express.static('public/html'));
app.post('/', function (req, res, next) {
console.log('start processing post data...');
next();
});
app.all('/', function (req, res) {
res.sendFile('./index.html', {
root: __dirname + '/public/html'
});
});
app.listen(2222);

Express only works on port 3000

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.

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