I have an issue rendering data in an EJS-template. The Object with data is present on the page but when I try to show a specific part of the data it won't render (like recept.title).
Router
router.get("/:slug", function(req, res) {
Recept.find({ slug: req.params.slug})
.exec(function(err, foundRecept) {
if(err || !foundRecept) {
req.flash("error", "Recept niet gevonden");
res.redirect("back");
} else {
res.render("recepten/recept", { recept: foundRecept });
}
});
});
When I render the whole object it will render (as shown below).
HTML File
<div class="row justify-content-center">
<div class="col-md-9">
<div class="card-img-top">
//this doesn't render
<img
class="card-img-top"
src="<%= recept.image %>"
alt="<%= recept.title %>"
/>
</div>
<div class="card-title">
<h1 class="h3"><%= recept.title %></h1>
<p>
//this will render the JSON object
<%= recept %>
</p>
</div>
</div>
</div>
Many thanks in advance.
Regards Jason
Sample Code:
index.js
const express = require("express")
const path=require("path");
const app = express()
app.set('views', path.join(__dirname, '/public'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
// being rendered res.render()
const port = 3000
app.get('/', (req, res) => {
var foundRecept=[{"title":"mango"},{"title":"apple"}]
res.render(__dirname + "/public/" + "index.html", { recept: foundRecept });
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="row justify-content-center">
<div class="col-md-9">
<div class="card-title">
<% for(var i=0; i < recept.length; i++) { %>
<h1 class="h3"><%= recept[i].title %></h1>
<% } %>
</div>
</div>
</div>
</body>
</html>
Related
My app.js file looks like this:
const express = require('express');
const exphbs = require('express-handlebars');
const app = express();
app.engine('hbs', exphbs.engine({
defaultLayout: 'main',
extname: '.hbs'
}));
app.set('view engine', 'hbs');
app.get('/', (req, res) => {
res.render('home');
});
app.listen(3000, () => {
console.log('The web server has started on port 3000');
});
app.get('/', function (req, res) {
res.render('home', {
post: {
author: 'John Smith',
image: 'https://picsum.photos/500/500',
comments: []
}
});
});
My home.hbs file looks like this:
<nav class="navbar navbar-dark bg-dark">
<a class="navbar-brand" href="#">Book Face</a>
</nav>
<div class="posts">
<div class="row justify-content-center">
<div class="col-lg-7" style="margin-top: 50px;">
<div class="card">
<img src="{{post.image}}"
class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">Posted by {{post.author}}</h5>
<ul class="list-group">
<li class="list-group-item">This is suppose to be a comment</li>
<li class="list-group-item">This is suppose to be a comment</li>
</ul>
</div>
</div>
</div>
</div>
</div>
And finally my main.hbs file looks like this:
<html lang="en">
<head>
<!-- <meta> tags> -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<title>Book Face</title>
</head>
<body>
<div class="container">
{{{body}}}
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</body>
</html>
When I run it locally, the html is rendering but the dynamic content from the array is not ie. {{post.image}} and {{post.author}} (in the post array in my app.js file). Did I do something incorrectly with the setup of my app.js file? I'm not getting any errors in the console.log.
I'm currently using NodeJs/Express and EJS for my web application. My goal was to build a simple page, with an input field, for testing XSS attacks. I'm not too experienced with building server-side applications. I was wondering how to send/retrieve the inputs from my text field.
And how do I add a CSS file?
// app.js
var express = require("express");
var path = require("path");
var routes = require("./routes"); // defines routes
var app = express();
app.set("port", process.env.PORT || 3000); // defines port
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: false}));
app.use(routes);
app.listen(app.get("port"), function() {
console.log("Server started on port: " + app.get("port"));
});
// routes.js
var express = require("express");
var router = express.Router();
router.get('/', function(req, res, next) {
console.log("Hello I'm on the start page here.");
res.render('index', {page:'Home', menuId:'home'});
});
router.get('/about', function(req, res, next) {
res.render('about', {page:'About Us', menuId:'about'});
});
module.exports = router; // export variables
// header.js
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>XSS</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
<div class="navbar navbar-default navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">XSS-Cross-Site-Scripting</a>
</div>
<ul class="nav navbar-nav navbar-right">
<li>About</li>
<li>Log in</li>
</ul>
</div>
</div>
<div class="container">
//footer.js
</div>
</body>
</html>
// index.js
<%- include ("_header.ejs"); %>
<h1 style="text-align: center;">Welcome to Cross-Site-Scripting</h1>
<div style="margin: auto; width: 50%; padding: 80px; border: 3px solid blue;">
<form id="contact-form" action="/send" method="POST">
<div style="text-align: center;" class="input-group">
<input type="text" class="form-control" name="userInput" placeholder="Enter something..." aria-label="Recipient's username" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" id="searchBTN" type="submit"><i class="fas fa-cart-plus mr-2"></i>Send</button>
</div>
</div>
</form>
<h1 style="text-align: center;"><%= userInput %></h1>
</div>
<%- include ("_footer.ejs"); %>
So, you are sending data to the server so you need to have a POST HTTP request.
app.post('/add', (req, res) => {
let inputText = [];
inputText.push(req.body.userInput)
res.render('index', {
inputText,
});
});
Now to get the value from the user input you need to write the below code in your index.ejs file
<% if (locals.inputText){ %>
<% inputText.forEach(function (text) { %>
<h5><%= text %></h5>
<% }) %>
<% } %>
Here is my EJS file
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Sart Plug</title>
<script src="http://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<link rel="stylesheet" href="/css/usrDashboard.css">
<link rel="icon" href="/images/plugimg.png" type="image/x-icon" />
</head>
<body>
<div class="container">
<div class="header">
Select Device
<div class="header-right">
Log Out
</div>
</div>
<div class="jumbotron" id="jumbo">
<p><%=data.noResult%></p>
<div class="row">
<% for(var i=0; i < data.result.length; i++) { %>
<div class="col-25">
<a href="/plugDashboard">
<p><img class="img-fluid" src="/images/plugimg.png" alt="Plug Image"></p>
<p><h3><%= data.result[i].device_name %></h3></p>
<p><h6><%= data.result[i].device_address %></h6></p>
</a>
</div>
<% } %>
</div>
</div>
</div>
</body>
</html>
Html view here
My routes are in the below route:-
app.get('/usrDashboard', checkAuthenticted, (req, res) => {
let email = req.user.email;
con.query("SELECT device_name, device_address FROM pluglist WHERE email ='"+ email +"' " , (err, result, fields)=> {
if(err) throw err;
console.log(result);
if (result.length === 0) {
res.render('usrDashboard',{data:{email: email,
result:result,
noResult:'You have no saved device'}});
}
else {
res.render('usrDashboard',{data:{email: email,
result:result}});
}
});
})
app.get('/plugDashboard', checkAuthenticted, (req, res) => {
console.log(req);
res.render('plugDashboard');
})
SO here I want, whenever I click on any of the div I want to print the mac id in log from the respective div in plugDashboard section. So is there any way to do so? I searched for many solutions none of them were helpful for me.
You can add new GET express route, for example:
router.get('/get_mac_info/:mac_id', function(req, res, next) {
res.json({
mac_id: 'test_id'
});
});
and after that just add ajax call on click event:
$(function () {
$(document).on('click', '.col-25', function (e) {
$.get('/get_mac_info/' + mac_id, function(data){
$('.print_container').text(data)
})
e.preventDefault();
});
});
I'm trying to build an app that lets me enter in information about an event and then have that pinned on a map. I'm stuck at the beginning though on actually saving the information. When I use Inspect in Chrome, it tells me it posted, but the data is blank. I'm pretty new to this kind of stuff and not sure where I'm going wrong.
The first file is the app.js where I set up the database, a simple partial schema, etc.
The second file is my dashboard.html that displays the map and the form. I was trying the onsubmit/javascript stuff which displays the data without refreshing the page, but ideally I want to be able to refresh the page and have the data still be posted somewhere.
Any help would be greatly appreciated! Thanks! :)
require('dotenv').config({ silent: false }); // Retrieve .env contents
var http = require('http'); // Basic HTTP functionality
var path = require('path'); // Parse directory paths
var express = require('express'); // Provide static routing to pages
var app = express();
var Router = require('router')
var router = Router()
var server = http.Server(app);
var port = 8080;
var app = setupExpress();
// Import mongoose module and connect the database
var mongoose = require('mongoose');
var mongoDB = 'mongodb://Username:Password#ds159180.mlab.com:59180/app-database';
mongoose.connect(mongoDB);
//Get the default connection
var db = mongoose.connection;
// Start server on port 8080
// localhost:8080
server.listen(port);
//Bind connection to error event (to get notification of connection errors)
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//Define a schema
var Schema = mongoose.Schema;
var EventSchema = new Schema({
eventName : String,
eventType : String
});
var Event = mongoose.model('Event', EventSchema);
app.post('/dashboard', function(req, res) {
res.json(req.body); // req.body is your form data
});
app.post('/dashboard', function(req,res){
var content = new Event({
eventName : req.body.eventName,
eventType : req.body.eventType
}).save(function(err,doc){
if(err){
return handleError(err);
} else {
console.log('your form has been saved');
}
})
});
function setupExpress()
{
// Set default path for views and public
var viewsDir = path.join(__dirname, 'views');
var publicDir = path.join(__dirname, 'public');
app.use(express.static(publicDir));
// Root page is login form
app.get('/', function(req, res)
{
res.sendFile('views/index.html', { root: '.' });
});
// Once logged in, home page is dashboard
app.get('/dashboard', function(req, res)
{
res.sendFile('views/dashboard.html', { root: '.' });
});
// Redirect to error page if there's an issue
app.use(function(err, req, res, next)
{
console.log(err.stack);
res.status(err.status || 500);
res.sendFile('/views/error.html', { root: '.' });
});
return app;
}
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<!-- Web browser tab title -->
<title>App</title>
<!-- Bootstrap Core CSS -->
<link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="../css/sb-admin-2.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="../vendor/morrisjs/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript"
src="http://www.your-domain.com/easy-comment/jquery.easy-comment.min.js"></script>
<title>App Tester</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-8" style="margin-top: 30px">
<div class="panel panel-default">
<div class="panel-heading text-center">
<i class="fa fa-map-marker fa-3x"> Add Event</i>
</div>
<div class="panel-body">
<div class="col-lg-6">
<form id="eventForm" method="post" onsubmit="return false">
<div class="form-group">
<label for="eventName">Event Name</label>
<input type="text" class="form-control" id="eventName" placeholder="Event name">
</div>
<div class="form-group">
<label for="eventType">Type</label>
<select class="form-control" id="eventType">
<option>Study Group</option>
<option>Food</option>
<option>Meeting</option>
<option>Danger</option>
</select>
</div>
<div class="form-group">
<label for="eventLocation">Location</label>
<select class="form-control" id="eventLocation">
<option>Location 1</option>
<option>Location 2</option>
<option>Location 3</option>
</select>
</div>
<div class="form-group">
<label for="eventNotes">Event Notes</label>
<textarea class="form-control" id="eventNotes" rows="2" placeholder="Add details about your event"></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
<div id="confirm"><div>
<script type="text/javascript">
var txt = document.getElementById("eventName");
document.getElementById("eventForm").addEventListener("submit", confirmdata);
function confirmdata(event) {
event.preventDefault();
var eventName = txt.value;
document.getElementById("confirm").innerHTML += '<p>Name: ' + eventName + '</p>';
}
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
You should use body-parser to change your data post from client to json
var bodyParser = require('body-parser')
app.use(bodyParser.json())
You can get json data via req.body
her is my app.js which is confugaration file of express.js
<
var express = require('express')
, argv = require("optimist").argv
, fs = require("fs")
, hbs = require("hbs")
, WatsonClient = require("watson-js");
var clientId = argv.key || '5b1cb9a9c097e1100eeeebaf66117265'
, clientSecret = argv.secret || '01b8417ac6872450'
, appPort = argv.port || '3000';
function cp(source, destination, callback) {
// Read a buffer from `source`
fs.readFile(source, function(err, buf) {
if (err) { return callback(err); }
// Write that buffer to the new file `destination`
fs.writeFile(destination, buf, callback);
})
}
var Watson = new WatsonClient.Watson({ client_id: clientId, client_secret: clientSecret });
var app = express();
app.configure(function() {
console.log('inside function');
// Set the location of views and type of view engine
app.set('views',__dirname + '/app/views');
console.log(__dirname + '/app/views');
app.set('view engine', 'html');
app.engine('html', require('hbs').__express);
console.log('after view');
// Set up a standard Express configuration
app.use(express.logger());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.session({
secret: "This is an example."
}));
app.use(app.router);
console.log('before public');
// Set the location of static assets
app.use(express.static(__dirname+'/public'));
console.log(__dirname+'/public');
console.log('after public');
});
app.get('/', function(req, res) {
res.render('layout');
});
app.post('/upload', function(req, res) {
cp(req.files.upload_file.filename.path, __dirname + req.files.upload_file.filename.name, function() {
res.send({ saved: 'saved' });
});
});
app.post('/speechToText', function(req, res) {
// Traditionally, you would store this access token somewhere safe like a database. For the purposes of this example, we're going to generate a new one on the first request and store it in the session so we don't have to deal with a database or tracking expiry and refreshing access tokens.
if(!req.session.accessToken) {
// !AT&T API: Get Access Token
Watson.getAccessToken(function(err, accessToken) {
if(err) {
// Handle an error getting an access token
res.send(err);
return;
} else {
req.session.accessToken = accessToken;
token.
Watson.speechToText(__dirname + '/public/audio/audio.wav', req.session.accessToken, function(err, reply) {
if(err) {
res.send(err);
return;
}
res.send(reply);
return;
});
}
});
} else {
Watson.speechToText(__dirname + '/public/audio/audio.wav', req.session.accessToken, function(err, reply) {
if(err) {
res.send(err);
return;
}
return;
});
}
});
app.listen(appPort);
console.log('AT&T Speech API Basic Walkthrough App started on Port ' + appPort + '.');
// !USAGE: node app.js --key= --secret= --port=
// !SETUP: Dependencies
/*
* Express: Minimal web application framework
* FS: Node.js File System module
* Optimist: Lightweight option parsing
* HBS: Express View Engine wrapper for Handlebars
* Watson.js: Simple API Wrapper for the AT&T Speech API
*/
and my layout.html is
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>AT&T Speech API Example: Basic Walkthrough</title>
<meta name="description" content="Application for the AT&T Speech API Deep Dive Presentation at DevLab 2012">
<meta name="author" content="Michael Owens">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="public/styles/bootstrap.css">
<link rel="stylesheet" href="public/styles/example-basic.css">
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js'></script>
</head>
<body>
<a onclick="Recorder.playBack('audio');" href="javascript:void(0);" title="Play">
Play
</a>
<div class="container">
<div class="row">
<div class="span12">
</div>
</div>
<div class="row">
<div class="span4">
<h2 id="progress-title">Progress (Step <span id="progress-step">1</span> of 5)</h2>
<div id="progress-indicator" class="progress progress-striped">
<div class="bar" style="width: 20%;"></div>
</div>
<ol class="progress-list">
<li id="progress-01" class="active">Access User's Microphone</li>
<li id="progress-02">Record Audio from Mic</li>
<li id="progress-03">Save Audio to File</li>
<li id="progress-04">POST File to AT&T Speech API</li>
<li id="progress-05">Receive Results from AT&T Speech API</li>
</ol>
<div>
<i class="icon-refresh"></i> Start Over
</div>
</div>
<div class="span8">
<h2>Current Status</h2>
<div id="status-mic" class="alert alert-info">
Audio Status: <strong>waiting</strong>
</div>
<div id="status-upload" class="alert alert-info">
File Status: <strong>waiting</strong>
</div>
<div id="control_panel">
<div class="btn-group">
<button id="button-connect" class="btn btn-large btn-success"><i class="icon-off icon-white"></i> <span class="action">Connect</span></button>
<button id="button-recorder" class="btn btn-large" disabled="disabled"><i class="icon-music"></i> <span class="action">Record</span></button>
<span id="button-save" class="btn">
<button disabled="disabled" class="btn btn-large"><i class="icon-download-alt"></i> <span class="action">Save</span></button>
<span id="save_button"><span id="flashcontent"></span></span>
</span>
<button id="button-transcribe" class="btn btn-large" disabled="disabled"><i class="icon-share-alt"></i> <span class="action">Transcribe</span></button>
</div>
</div>
<div id="transcribe-container">
<h2>Speech API Response</h2>
<div id="transcribe-response"></div>
</div>
</div>
</div>
<form id="uploadForm" name="uploadForm" action="/upload" >
<input name="authenticity_token" value="xxxxx" type="hidden">
<input name="upload_file[parent_id]" value="1" type="hidden">
<input name="format" value="json" type="hidden">
</form>
<script type="text/javascript" src="public/scripts/swfobject.js"></script>
<script type="text/javascript" src="public/scripts/example-basic.js"></script>
</div>
</body>
</html>
When i run app.js on node in cmd, it gives me error of not able to load static files i.e js and css files but it load view part i.e layout.html
exact errors is
<
GET h://ip:3000/public/scripts/swfobject.js 404 (Not Found)
GET h://ip:3000/public/scripts/example-basic.js 404 (Not Found)
GET h://ip:3000/public/styles/bootstrap.css 404 (Not Found)
GET h://ip:3000/public/styles/example-basic.css 404 (Not Found)
>
ip -localhost
h -https
my foldr structute is
example(parent folder)
subfolders
app/views/layout.html(code is given above)
public/scripts/js files
public/styles/css files
app.js(code is given above)
all the above subfolder(app,public,app.js) at the same level
so please suggest me some thing
It should work if you remove the 'public' from your URLs, like:
<link rel="stylesheet" href="/styles/bootstrap.css">
<link rel="stylesheet" href="/styles/example-basic.css">
You setup the static directory to be /public so its going to look in there for static resources. You did that here:
app.use(express.static(__dirname+'/public'));
When you add public to those URLs, it will be looking in /public for a folder called public, which it won't find. It will however find a folder called styles.