I'm trying to include header.ejs and footer.ejs file with my home.ejs file.
A home.ejs file is located in views folder and the others are located in views/partials.
While including the file I get the error:
SyntaxError: Unexpected identifier in D:\wamp64\www\Training\node_pug\views\home.ejs while compiling ejs
I am a beginner in nodejs.
header.ejs
<DOCTYPE! html>
<html>
<head>
<title>
<link rel="stylesheet" hreff="app.css">
</title>
</head>
<body>
footer.ejs
</body>
</html>
service.js
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use(express.static('public'));
var session = require('express-session');
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
const ejsLint = require('ejs-lint');
app.get('/', function(request, response) {
response.render('login');
});
app.get('/home', function(request, response) {
response.render('home');
});
app.post('/auth', urlencodedParser,function(request, response) {
var username = request.body.username;
var password = request.body.password;
if(username == 'admin')
{
//response.redirect('ejs/home');
response.render('home');
}else{
response.render('login');
}
});
var server = app.listen(8080,function(){
console.log('server is running...');
});
home.ejs
<% include partials/header %>
<h1>welcome</h1>
<% include partials/footer %>
From the docs: The recommended way to include a file is as below:
<%- include('partials/header') %>
<h1>welcome</h1>
<%- include('partials/footer') %>
The docs state that
NOTE: Include preprocessor directives (<% include user/show %>) are not supported in v3.0+.
You are probably using a v3.0+ version of EJS hence the error you are experiencing. The snippet above should solve your issue.
If you are using express 4.X you should probably use this syntax in your home.ejs.
<%- include partials/header.ejs %>
<h1>welcome</h1>
<%- include partials/footer.ejs %>
Related
I am currently towards the end of my project but there is one error I am receiving still. I cannot seem to figure out why I am receiving the error:
"Failed to load resource: the server responded with a status of 404
(Not Found)".
Below is my file layout, server.js and the script tag. I have my layout the same as all the other projects I have made in the past but for some reason this error keeps popping.
server.js
"use strict";
// DEPENDENCIES
require("dotenv").config();
const express = require("express");
const session = require("express-session");
const passport = require("passport");
const path = require("path");
const ejs = require("ejs");
const logger = require("morgan");
var createError = require("http-errors");
var cookieParser = require("cookie-parser");
const flash = require("connect-flash");
const favicon = require("serve-favicon");
// ROUTES REQUIRED
const main = require("./routes/main");
const about = require("./routes/about");
const contact = require("./routes/contact");
const profile = require("./routes/profile");
const pricing = require("./routes/pricing");
const help = require("./routes/help");
const login = require("./routes/login");
const signup = require("./routes/signup");
const forgot_password = require("./routes/forgot-password");
// PORT
const port = 3000;
const app = express();
// COOKIES AND SESSION
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
})
);
app.use(passport.initialize());
app.use(passport.session());
// DATABASE
require("./config/database.js");
// PASSPORT AUTHENTICATION
require("./config/passport.js");
// VIEWS SETUP
app.set("views", path.join(__dirname + "/views"));
app.set("view engine", "ejs");
app.set("view cache", false);
// MIDDLEWARE
app.use(favicon(__dirname + "/public/favicon.ico"));
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use("/public", express.static(path.join(__dirname + "/public")));
app.use(flash());
// ROUTES
app.use("/", main);
app.use("/about", about);
app.use("/contact", contact);
// PRICING
app.use("/pricing", pricing);
// PROFILE
app.use("/profile", profile);
app.use("/help", help);
app.use("/login", login);
app.use("/signup", signup);
app.use("/forgot-password", forgot_password);
// Logout
app.get("/logout", function (req, res) {
res.clearCookie("connect.sid");
res.redirect("/");
});
app.listen(process.env.PORT || port, (err, done) => {
if (!err) {
console.log({ message: "success!" });
} else {
return err;
}
});
home.ejs(home page layout with scripts.)
--------------------------------------------------------------------------
<section class="ad-analytics">
<div class="container-fluid ad-analytics__contain">
<div class="row ad-analytics__row">
<div class="col-md-6" id="meetings-img-holder">
<!-- bg-img holder -->
</div>
<div class="col-md-6 ad-analytics__textbox">
<div class="col-sm-12 ad-analytics__info">
<h1 class="h2">Analytical Precision</h1>
<p>
Getting ahead of the curve is the best way to scale above the
compeititon. With our machine learning tools, you can leverage
your data and get real insight on what your customers want from
you.
</p>
<a
class="btn btn-outline-light btn-sm"
href="/machine-learning"
role="button"
>Get Started</a
>
</div>
</div>
</div>
</div>
</section>
<%- include('partials/footer.ejs') %>
<%- include('partials/scripts.ejs') %>
</body>
</html>
------------------------------------------------------------------------------------
(Inside partials/script.js)
<script
src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"
></script>
<script type="javascript" src="/server.js"></script>
File Layout
You shouldn't use <script> tags to import server side files, like for an example server.js, this file is used to run the node server
let's say you make a script for home page, you need to save it inside /public and the send it to client to be interpreted by the browser by adding it to partials/scripts.ejs
example
<script type="javascript" src="/home_script.js"></script>
the path would be
public/home_script.js
Edit:
it feels like you're still a bit confused so i'll take a example
in server.js you have
const main = require("./routes/main");
app.use("/", main);
think about the file main.js like taking a function from server.js and moving it to a single file
now in main.js i'm guessing you have a function like this:
router.get('/', (req,res,next) => {
res.render('home.ejs')
})
the code above is part of server side code and shouldn't be sent to the user(the client)
now inside home.ejs
you have your partials and then a section for scripts
<script type="javascript" src="/bootstrap.bundle.min.js"></script>
<script type="javascript" src="/home_script.js"></script>
this file home_script should contains stuff that you want to do once the page arrives the user (we call this client side)
as an example:
if you have button and you want to do something when you click you write that part of javascript inside home_script.js
When I pass the data dictionary to the EJS template, it formats the decimals as integers. What's the recommended way to fix it?
const express = require('express');
const app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
let data = {
lat: 42.0,
lng: 78.0
}
res.render('pages/index',data);
});
app.listen(8080);
The index.ejs template:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
test <%= lat %>
</body>
</html>
The answer:
test <%= lat.toPrecision(8) %>
I'm getting the page redirects correctly however when I'm going to list this result in the front-end the value is not shown just the command of the EJS in my front-end view.
I've tried to pass the output value in several different ways but none worked...
This my root files.
My index.js
var http = require('http');
var express = require('express'),
mongoose = require('mongoose'),
ejs = require('ejs'),
nunjucks = require('nunjucks'),
path = require('path'),
mysql = require('mysql'),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
logger = require('morgan');
var errorHandler = require('errorhandler');
app.use(logger('dev'));
app.use(bodyParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
import config from "./config/config";
import mongodb from "./config/mongodb";
import passport from "./config/passport";
import * as setup from "./middleware/setup";
import app from "./config/express";
import routes from "./routes";
import User from './models/User';
export function start() {
return new Promise((resolve, reject) => {
mongodb().then((db) => {
let server = http.createServer(app);
// save references
app.db = db;
app.server = server;
app.config = config;
// init passport
passport(app);
// register setup check middleware
app.use(setup.check);
// setup routes
routes(app);
// start server
app.server.listen(config.server.port, (err) => {
if (err) {
return reject(err);
}
resolve(app);
});
}, reject);
});
};
app.set('views', __dirname + '/templates');
app.engine('html', require('ejs').renderFile);
var api = express.Router();
app.use('/', api);
api.get('/test-ejs', function (req, res) {
res.render('test.html', { title: 'Return sucess!' });
});
api.get("/templates",function(req, res){
var path = __dirname + '/templates/';
res.sendFile(path + "index.html");
});
My HTML template test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test EJS</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- HTML5 shim, for IE6-8 support of HTML elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- styles -->
<link href="stylesheets/style.css" rel="stylesheet">
</head>
<body>
<%= title %>
</body>
</html>
Thank for helping me! xD
You are using .html file for rendering the data but in your app.js you have defined it as .ejs under app.engine line.
So either you have change the .html file type to .ejs or you have to replace your app.engine line with this
app.set('view engine', 'html');
I am newbie to Node.js trying to learn through tutorials found online using Netbeans.
When I do: http://localhost:9080/ I see the Date and the color as expected. But when I try to do http://localhost:9080/add, to see the app.post part, I get HTTP 404 error.
Could anyone let me know what am i doing wrong.
Thanks in advance,
ind.ejs
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<h1> my app </h1>
<%= new Date() %>
Color is:
<%= test %>
</body>
</html>
index.js:
'use strict';
module.exports = require('./lib/express');
var http = require('http');
var express = require('express');
var path = require('path');
var ejs = require('ejs');
var app = express();
var tropo_webapi = require('tropo-webapi');
var bodyParser = require('body-parser');
var test;
var app = express();
//app.use(bodyParser());
app.set('view engine','ejs');
app.set('views', path.join(__dirname,'views'));
app.get('/',function(req,res){
var test = 'red';
console.log('test in get is :' + test);
res.render('ind.ejs',{test:test});
});
app.post('/add',function(req,res){
test = 'blue';
console.log('test in post is :' + test);
res.render('ind.ejs',{test:test});
});
app.listen(9080, function(){
console.log('Ready on port 9080');
});
app.get is for the 'GET' http verb, which is used by default. app.post is triggered for the 'POST' http verb, which can be done using forms:
<form action="/add" method="post"><button type="submit">go</button></form>
I am trying to run Cheerio on node.js with ejs as my template. Whenever I run the server, I get 'undefined' at the the 'console.log'. Given below is my code.
Server side
app.js
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path')
, request = require ('request')
, cheerio = require ('cheerio');
var $ = cheerio.load('<ul id="fruits">...</ul>');
var app = express();
console.log($('[class = "orange"]').attr('id'));
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
var temp = $('[class="orange"]').attr('id');
app.get('/data', function(req, res){
console.log(temp);
res.send(temp); //replace with your data here
}).listen(3000);
index.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<input type="button" id="stopButton" value="Stop Listening"/>
<p>Welcome to <%= title %></p>
<ul id="fruits">
<li id= "1" class="apple">Apple</li>
<li id = "2" class="orange">Orange</li>
<li id = "3" class="pear">Pear</li>
</ul>
<script type="text/javascript">
$(document).ready(function () {
$('#stopButton').click(function () {
$.get('http://localhost:3000/data', {}, function (data) {
$('[id="2"]').text(data);
});
});
});
</script>
</body>
</html>
In the end what I wish to do is to send a value 'temp' at the press of a button 'stopButton' to the HTML page.
If you want to render html output from cheerio, cheerio describe the following way.
var cheerio = require('cheerio'),
$ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
$.html(); // !!!You need this step!!!
Then on client side, use $('[id="2"]').html(data); instance of using $('[id="2"]').text(data);