"ejs.render" is calling next route - node.js

when I enter in http://localhost/client, display 404.
app.get('/client', function(req, res) {
...
ejs.render('any template', {});
...
res.end();
});
app.get('*', function(req, res) {
console.log('404');
...
});
but if I remove "ejs.render" and put res.end('any html') works.
How can i use "ejs.render" and not call 404? Thanks. It's a bug.

You need to set ejs for use EJS with express.
The Express application generator uses Jade as its default, but it also supports several others (Like ejs, pug, etc).
For example:
var express = require('express');
var app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
// use res.render to load up an ejs view file
// index page
app.get('/client', function(req, res) {
res.render('pages/index'); //does not needs ejs extension
});
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(8080);
console.log('8080 is the magic port');
When you make a request to the home page, the index.ejs file will be rendered as HTML.
See the official documentation here.

Related

How to use route for html file already served as static

I use passport.js to authenticate user after he enters login page. To keep user logged in when he returns to home page i'm going to use something like:
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res){
if(req.user){
// connect to database ....
} else{
res.sendFile(__dirname +'/index.html');
}
});
Note that index.html file is inside "public" folder. Recently i realized that having a code like above, node.js doesn't use app.get('/'....) route but it serves index.html directly. So i'm unable to check if req.user exists. Any suggestion?
As You might understand express.static handles index.html before Your router.
But You cannot avoid express.static also (otherwise You have to use nginx or write own static file output).
So You've to re-think Your folder structure or have to develop 2 separate apps: api (backend) and frontend (that will request to api for data)
In context of Your question I wrote an example app where I organize assets, html files and app routes:
1) Have such folder structure:
2) and example app.js :
'use strict';
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
app.set('trust proxy', 1);
// attaching renderer
app.engine('.html', require('ejs').renderFile); // ejs renderer will render .html files as ejs files
app.set('view engine', 'html'); // views has .html extension
app.set('views', __dirname + '/public'); // views live in public folder
// attaching common middlewares
app.use('/assets', express.static('public/assets')); // our static assets will live in public/assets folder
app.use(cookieParser());
app.use(bodyParser());
// implement and attach passport auth somewhere (:
// remove it after passport has been attached:
const authorizeUser = (req, res, next) => {
req.user = {id: 1, username: 'test'};
next();
};
app.get('/', authorizeUser, (req, res) => {
res.render('index', {user: req.user}); // render get index.html from views folder (see above)
});
app.listen(8080, () => {
console.log('App listening');
});
p.s. download example app from here (don't forget to call npm i inside extracted folder (; )
p.s. implement passport.js Yourself

Using EJS in Express

My EJS files are in a views folder which is defined in the app.js file as follows:
app.set('views', path.join(__dirname, 'views'));
But currently every time I add a new page I have to specify the route as follows:
/* GET login page */
router.get('/login', function(req, res, next) {
res.render('index', { title: 'Express' });
});
Where router is express.Router(). Is there a better way? I can't believe I need to add this routing code for every page. What's the best practice for EJS?

Node JS Pass a Variable to Jade / Pug

For some reason I can't pass a variable to the pug template with Node JS.
app.get("/", function (req, res) {
res.render('index', { hello : 'Hey'} )
})
....
extends layout.pug
block content
h1 #{hello} guy
This just returns "guy" in the index.html file
I think you are using JADE coding (#{hello}) with "pug"(updated jade) plugin with static .html -- completely wrong.
Follow the lines below:
Use this first
app.set('views', __dirname + '/public/views');
app.set('view engine', 'pug');
Then pass this to first visit
app.get('/', function (req, res) {
res.render('index', { title: 'Hey', message: 'Hello there!'});
});
Then echo in template file "index.pug" in "/public/views"
html
head
title= title
body
h1= message
Try this.. works for me.
nodejs part / index.js
const router = require('express').Router();
router.get('/', (req, res, next) => {
const testObj = {hello: 'Hey'};
res.render('index', { testObj: JSON.stringify(testObj) });
});
pug/jade part / (index.pug)
script.
var testObj = !{testObj};
i'm using pug version: 2.0.3

Node Express Routing not working as exprected

app.js:
var routes = require('./routes');
app.use(express.urlencoded());
app.use(app.router);
app.get('/', routes.index);
And some more use statements.
./routes/index.js:
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
exports.impressum = function(req, res){
res.render('impressum', { title: 'Impressum' });
};
And in ./views/ I have index.jade and impressum.jade
Calling http://localhost:3000/ shows the index.
But I can't reach the impressum page at all. Any clues?
As damphat mentions you need to wire up a route to your impressum page. You'll have to put in a route for each page you want your app to respond to.
I did a screencast that goes into Express routing. You can check it out-- it might be of use. Also the Express documentation is useful.

Node.js sending html file doesn't load linked files (css, js)

I am trying to make az ExtJS application with a Node.js server. My server code currently looks like this:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
When I open localhost:3000 in a browser, the html file is load, but not correctly. Checking in firebug I see that itt cannot find the linked files in html. For example
"NetworkError: 404 Not Found - http://localhost:3000/ext-4/ext-debug.js".
This is quite logical, since the file doesn't exist on that URL. My question would be how to fix this issue, so it could find every single linked file on my filesystem.
I'm clearly doing something wrong or missing something, I am totally new in node.
Doesn't look like you're configuring Express' static file handler.
Try adding this code:
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
It would go right after var app = ... like this:
var express = require('express');
var app = express();
app.configure(function() {
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.bodyParser());
app.use(express.logger("short"));
});
app.get('/', function (req, res) {
res.sendfile(filedir + '/index.html');
});
app.get('/employees', function(req, res){
console.log("hello");
});
app.listen(3000);
And then place your static files under the ./public directory.
You'll want to use some static middleware such as: http://www.senchalabs.org/connect/static.html
note express inherits connect so you can
app.use(express.static(filedir));
Or the full thing:
var express = require('express');
var app = express();
app.use(express.static(filedir));
app.get('/employees', function(req, res){
console.log("hello");
res.send("hello");
});
app.listen(3000);

Resources