Undefined while using Cheerio on Node.js - node.js

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

Related

Where to put Handlebars.registerHelper function in node.js project?

I want to increase "totalPrice" by 10 and then display it in handlebars templates . Here z some snippet of my handlebar file.
checkout.hbs
<ul class="shipping__method">
<li>Shipping <span>$ 10</span></li>
</ul>
<ul class="total__amount">
<li>Order Total <span>Rs. {{increasePrice totalPrice}}</span></li>
</ul>
For that i write this in my app.js file
var expressHbs = require('express-handlebars');
app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs'}))
app.set('view engine', '.hbs');
expressHbs.registerHelper ('increasePrice', function (price) {
price+=10;
return price;
})
And then i got error expressHbs.registerHelper is not a function. Then i came to know to write it like this
var hbs = expressHbs.create({
helpers: {
increasePrice: function(price) {
price+=20;
return price;
}
}
})
And then i got error like "missing Helper: "increasePrice" ".
👨‍🏫 You see this code below 👇, an example code using express and express-handlebars:
index.js
var express = require('express');
var app = express();
var expressHbs = require('express-handlebars');
app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs'}))
app.set('view engine', '.hbs');
var hbs = expressHbs.create({});
// register new function
hbs.handlebars.registerHelper('increasePrice', function(price) {
price+=10;
return price;
})
app.get('/', (req, res) => {
res.render('home', {
layout: false,
totalPrice: 300,
});
})
app.listen(3000, () => {
console.log('Server is up');
});
Now create file home.hbs in views, and put this code below 👇 in there.
home.hbs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Example APP</title>
</head>
<body>
<ul class="shipping__method">
<li>Shipping: Total Price <span>$ {{ totalPrice }}</span></li>
</ul>
<ul class="total__amount">
<li>Order Total <span>Rs. {{increasePrice totalPrice}}</span></li>
</ul>
</body>
</html>
From the code above 👆, I hope you can understand now, where you have to put your function.
For an example: You can see on my codesandbox
I hope it's can help you 🙏.

ejs compilation error in node.js express app

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 %>

When rendering ejs file, it does not show properly

I am trying to render ejs file from nodejs express.
But it shows html codes with thes character � everywhere.
let express = require('express');
let app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index', { title: 'The index page!' })
});
And index.ejs is
<html>
<head>
<title><%= title %></title>
</head>
<body>
welcome <%= title %>;
</body>
</html>
What did do I do wrong?
The server needs to be started
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.render('index', { title: 'The index page!' })
});
app.listen(3000);

Issue with rendering express template with node.js

I am facing an issue rendering the 'EJS' Express template while running the node.js server. I have provided the codes below. As you can see, I am implementing the http.createServer(function (req, res) to read and write messages to the client. But the template holding the HTML code doesn't get rendered. The main objective of the code is for the client to post a message 'Hello from Client' to the server and the server responding to the client with 'Hello from Server'.
app.js (Server Side)
/**
* 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 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);
http.createServer(function (req, res) {
var body="";
console.log('Request received: ');
req.on('data', function (chunk) {
body +=chunk;
});
req.on('end', function(){
console.log("Body: "+body);
res.write('Hello from Server');
res.end();
});
}).listen(3000);
index.ejs (Client Side)
<!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="Button1"/>
<input type="button" id="stopButton2" value="Button2"/>
<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 () {
var formData = {data: "Hello from Client"};
$.ajax({
url: 'http://localhost:3000',
dataType: "json",
type: 'POST',
data: formData,
jsonpCallback: 'callback',
success: function (data, textStatus, jqXHR) {
var ret = jQuery.parseJSON(data);
console.log(ret.msg);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("Error received");
}
});
});
</script>
</body>
</html>
package.JSON
{
"name": "NewProject",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.2.6",
"ejs": "*"
}
}
Earlier I had tried using app.get which had worked.
What is the primary difference between using app.get(), request() and http.createServer(). When should we use what?
It's not gonna work that way. Have a loo at the docs:
http://expressjs.com/starter/hello-world.html
For example:
var express = require('express');
var bodyParser = require('body-parser')
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.post('/hello', function (req, res) {
res.send("Hello from server");
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
Also, please use a recent version of Express, yours is outdated.

Cannot read data at node

I am trying to establish a communication between JQuery on the client side and node on the server side. I have used ajax with callback but the
'req.on('data', function (data) {'
doesn't seem to work.
Given below is the code:
Client side:
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="Button1"/>
<input type="button" id="stopButton2" value="Button2"/>
<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 () {
$.ajax({
url: 'http://localhost:3000',
dataType: "jsonp",
data: '{"data": "Hello from Client"}',
type: 'POST',
jsonpCallback: 'callback',
success: function (data) {
var ret = jQuery.parseJSON(data);
console.log(ret.msg);
$('[class="apple"]').html(ret.msg);
}
});
});
</script>
</body>
</html>
Server side:
node.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 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);
http.createServer(function (req, res) {
var body="";
console.log('Request received: ');
req.on('data', function (chunk) {
body +=chunk;
});
req.on('end', function(){
console.log("Body: "+body);
res.write('Hello from Server');
res.end();
});
}).listen(3000);
I do get the ''Request received: '' on the server side console log. Also, I am able to view the 'Hello from Server' on the HTML.
Any help would be appreciated.
It seems like you forgot to end your message: res.end();
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.on('data', function (data) {
console.log(data);
res.write('Hello from Server');
res.end();
});

Resources