node.js variables will not be parsed - javascript

i am new in node.js and express.
in my test app the html variables will not be parsed.
what is the problem?
server.js
enter var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({
extended : true
}));
app.use(express.static(__dirname));
app.get('/', function(req, res) {
res.render('index', {
wert : 'hallo'
});
});
app.post('/', function(req, res) {
var wert = req.body.wert;
var html = 'Hallo: '+wert+'!\n'
+ 'Mach\'s nochmal!';
res.send(html);
});
app.listen(8882);
console.log('Server port: 8882');
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Startseite</title>
</head>
<body>
<p>Hallo <%= wert %>, dies ist mein kleiner Webserver!</p>
<br>
<form action="/" method="post">
<input type="text" width="40" name="wert" value="<%= wert %>">
<input type="submit" value="submit">
</form>
</body>
</html>
the value parameter <%= wert %> in the view is not parsed.
why? how to do it?
thank you
jet

Express doesn't come with a view-engine by default. You need to add one, in your case EJS.
Using the command line, type:
npm install ejs
server.js now becomes:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(bodyParser.urlencoded({
extended : true
}));
app.use(express.static(__dirname));
app.get('/', function(req, res) {
res.render('index', {
wert: 'hallo'
});
});
app.post('/', function(req, res) {
var wert = req.body.wert;
res.render('index', {
wert: wert
});
});
app.listen(8882);

thank you ben,
your ejs configuration was good.
I had to install express, ejs, body-parser. that was ok.
then i had to remove the line with app.use(express.static(__dirname));
and i had to change
app.set('views', __dirname + '/views');
to
app.set('views', __dirname);
for my original path.
then everything was ok!
greez
jet

Related

Node.js/Express.js request body is undefined. body-parser is installed and imported

I am trying to get the text that is typed in by the user in my html input field and push it into an array. But the body of my request ist always empty. I already tried changing the order of code but it is not helping. Where is the Problem?
app.js file:
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const gameRouter = require('./routes/game.js');
const siteRouter = require('./routes/site.js');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/game', gameRouter);
app.use('/', siteRouter);
app.listen(3000);
game.js file in the folder routes:
const express = require('express');
const router = express.Router();
const games = [];
router.get('/game', (req, res, next) => {
});
router.post('/create', (req, res, next) => {
console.log(req.body);
games.push({game: req.body.game})
res.redirect('/');
})
module.exports = router;
ejs file for html generating:
<%- include('./includes/head.ejs') %>
</head>
<body>
<%- include('./includes/nav.ejs') %>
<h1>Create a new Game</h1>
<main>
<form action="/game/create" method="POST">
<div>
<input type="text" id="game">
<button type="submit">start</button>
</div>
</form>
</main>
<%- include('./includes/end.ejs') %>
You need to add name attribute to the input element:
<input type="text" name="game" id="game">
Use this line before app.use():
// For parsing a JSON file
app.use(bodyParser.json())
// For parsing parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: false}));

Can get ejs file to render, im using node

I would like to get my ejs file to display on the server ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
<html>
<head><title><%= title %></title></head>
<body>
welcome <%= user%>;
</body>
</html>
//////////////////////////////////////////////////////////////////////////////////////
var express = require("express");
var app = express();
var port = process.env.PORT || 3000;
app.set('view engine', 'ejs');
app.get("/", function(req, res){
res.sendFile(__dirname + '/about.html');
});
app.get("/news", function(req, res){
res.sendFile(__dirname + '/news.html');
});
//app.get('/student/:id', function(req, rep){
// rep.render('student', { name : student[req.params.id] , id : req.params.id});
//});
//app.get('/student', function(req, res) {
// res.render('student');
//});
app.get('/', function(req, res){
res.render('student',{user:"John Smith"})
});
app.listen(port);
You have conflicting routes configured for '/'.
Do you want to use a separate route for student? like following
app.get('/student', function(req, res){
res.render('student',{user:"John Smith"})
});
You need to create a views folder, and put your .ejs template in there. For example if you create the file views/student.ejs , then you can use this route to render this ejs file
app.get('/', function(req, res){
res.render('student', {user:"John Smith"})
});
Scotch.io tutorial

Handlebars/Node/Express Can't load files

So I'm working on developing a Node/Express webapp for basic CRUD operations and I'm having a hard time implementing Handlebars within the project.
When I try to use handlebars none of my stylesheets from my .hbs (previously .html) pages are loading.
Here's the file tree:
Here is the error:
And here is an example of the script import statements from
index.hbs
<!-- Bootstrap -->
<link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
And Finally here is the server.js file
var express = require('express'),
bodyParser = require('body-parser'),
path = require('path'),
mysql = require('mysql'),
dbconfig = require('./config/database'),
exphbs = require('express-handlebars');
var connection = mysql.createConnection(dbconfig.connection)
connection.query('USE ' + dbconfig.database);
var app = express();
//Body Parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//Set static path
//app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.static(__dirname + '/public'));
//app.set('views', __dirname + '/views');
//app.use('/views', express.static(path.join(__dirname, '/views')));
app.engine('hbs', exphbs({defaultLayout: false}));
app.set('view engine', 'hbs');
app.set(express.static(__dirname + '/public'));
//app.use('/views/vendors', express.static(path.join(__dirname, '/views/vendors')));
//app.use(express.static(__dirname + '/public/vendors'));
app.get('/', function(req, res) {
res.render('index');
connection.query("SELECT * FROM Student", function(err, rows){
console.log(rows);
});
});
app.listen(80, function() {
console.log('we are live on 80');
});
I tried using various static paths from other things I found on SO but wasn't able to get any of them to work.
Any help would be greatly appreciated!!
Thanks!
Fixed my problem by adding the following line above my app.get('/'....
app.use("/vendors",express.static(__dirname + "/vendors"));
app.use("/build",express.static(__dirname + "/build"));
app.use("/images",express.static(__dirname + "/images"));
app.get('/', function(req, res) {
I think that can be possible that the problem is in the handlebars configuration, please look at a configuration like this:
app.engine('.hbs',exphbs({
defaultLayout:'layouts',
layoutsDir:path.join(app.get('views'),'layouts'),
partialsDir:path.join(app.get('views'),'partials'),
extname:'.hbs',
helpers: helpers
}));
app.set('view engine','hbs');
maybe in yours it would be:
app.engine('hbs', exphbs({defaultLayout: false, extname:'.hbs',}));
if you are usign app.set(express.static(__dirname + '/public'));
try to put in the public folder your styles for example the bootstrap folder, and then all you have to do is call it in this way:
<link href="/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

Node js : Using Handlebars and Bodyparser together

In this basic program I would like to get user input using 'body parser' and then enter that input via handlebars onto the index page. I have attempted many times but can't seem to acheive it. Also does handlebars and bodyparser go together or should I be using something different.
Template:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<header>
<h1>Bodyparser and Handlebars</h1>
</header>
<form method="post" action="/">
<input type="text" name="name1">
<input type="submit" value="Submit">
</form>
{{test}}
</body>
</html>
Node.js
var express = require('express');
var app = express();
var handlebars = require('express-handlebars');
var path = require("path");
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.set('view engine', 'html');
app.engine('html', handlebars({
defaultLayout: 'base',
extname: '.html'
}));
app.use(express.static(path.join(__dirname, 'public'))); //public directory
app.get('/index', function(req, res) {
res.sendFile('index.html', { root: __dirname });
});
app.get('/', function (req, res) {
res.render('index', {
test: req.body.name1});
});
app.post('/', function(req, res){
console.log(req.body.name1);
});
app.listen(3000);
Your post to / should be:
app.post('/', function(req, res){
res.render('index', {
test: req.body.name1});
});
And you are done.
Body-parser and handlebars work perfect togheter. Body-parser allows you to collect the request data inside the router controller and handlebars is a template engine that render the variables and more stuff.
You need to pass the text that you want to display to the POST router controller.
<form action="/" method="post">
name1: <input type="text" name="name1"><br>
<input type="submit" value="Submit">
</form>
Put that form in other view or anywhere you want
Inside the controller pass the request parameter to handlebars:
app.post('/', function(req, res){
res.render('index', {
test: req.body.name1});
});

Node Ejs module, include not working

Im having some trouble including a html snippets into my index.html .
I have tried to follow, the ejs documentation but I just can't seem to make it work.
Directory Structure:
project
-public
--assets
---css
---images
---js
--Index
---index.html + index.css and index.js
--someOtherPageFolder
-views
--partials
---partials1.ejs
--index.ejs
--layout.ejs
-server.js
This is my server.js (NEW):
var express = require("express");
var partials = require("express-partials");
var http = require('http');
var path = require('path');
var app = express();
app.get("/", function(req, res) {
res.redirect("index");
});
app.configure(function(){
app.set('port', process.env.PORT || 8888);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(partials());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
http.createServer(app).listen(app.get('port'), function(){
console.log('App listening on port ' + app.get('port'));
});
This is my test.ejs:
<h1>This is test!</h1>
And this is where I want the html snipp to go:
<div id="sb-site">
<div class="">
<p>Not test</p>
<%- include test.html %>
</div>
</div>
What am I doing wrong?
Is there also a way for me to do this and use .html instead of .ejs (Im using eclipse and it doesn't support .ejs files)
With include you shoud do like this:
<%- include ("./partials/footer") %>
Express 3 breaks ejs partials, use express-partials instead.
// Include it like so with your other modules
var express = require("express");
var partials = require('express-partials');
var server = express();
// Finally add it into your server conviguration
server.configure(function(){
server.set('view engine', 'ejs');
// Include partials middleware into the server
server.use(partials());
});
In your .ejs views, enjoy the luxury like so...
<%- include ../partials/header %>
<section id="welcome">
Welcome
</section>
<%- include ../partials/footer %>
Also, rather than setting the ejs module to read .html just follow this answer to get eclipse to render .ejs as .html. how do i get eclipse to interpret .ejs files as .html?
As an example, this is how a basic express structure is setup...
project
--public
--views
----layout.ejs
----index.ejs
----partials
------partial1.ejs
--server.js
server.js would look like...
var express = require('express'),
partials = require('express-partials'),
http = require('http'),
path = require('path');
var app = express();
// all environments
app.configure(function() {
app.set('port', process.env.PORT || 3838);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Middleware
app.use(partials());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
http.createServer(app).listen(app.get('port'), function(){
console.log('App listening on port ' + app.get('port'));
});
Your route would look like...
server.get("/", function(req, res) {
res.render("index");
});
And finally, your layout.ejs...
<html>
<head>
<title></title>
</head>
<body>
<%- body %>
</body>
</html>
and index.ejs ...
<div id="index">
<%- include partial1.ejs %>
</div>
If you need a reference to the working example, here it is
You need to use the new include syntax:
before: <%- include test.html %>
after: <%- include ('test') %>

Categories