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();
});
Related
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 🙏.
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);
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.
I'm new to node , and I'm having so much trouble uploading a photo ;
here are my code :
var express = require("express"),
bodyParser = require('body-parser'),
app = express();
app.set('views', __dirname + '/Views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded());
app.post('/upload',function(request,response){
response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
console.log(request.body);
response.end();
});
And here is the index.html Where I have my form :
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>Test Drive Upload</h1>
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="text" name="username">
<input type="password" name="password">
<input type="file" name="thumbnail">
<input type="submit">
</form>
</body>
</html>
When ever I try to upload a photo and hit submit , I look at my console to see what is in the body ( I expect some hints to a file ! ) but here is the console after hitting the submit
{ username: '', password: '' }
There is No sign of any file or image
I've also tried this :
console.log(request.files);
console.log(request.form);
but both will throw undefiend in the console
Version 1 without using body parser:
var express = require('express');
var http = require('http');
var app = express();
app.use(express.static('./public'));
app.configure(function(){
app.use(express.methodOverride());
app.use(express.multipart({
uploadDir: './uploads',
keepExtensions: true
}));
});
app.use(app.router);
app.get('/upload', function(req, res){
// Render page with upload form
res.render('upload');
});
app.post('/upload', function(req, res){
// Returns json of uploaded file
res.json(req.files);
});
http.createServer(app).listen(3000, function() {
console.log('App started');
});
Version 2 with using body parser:
var express = require('express')
var app = express()
app.use(express.bodyParser({ keepExtensions: true, uploadDir: '/uploads' }))
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
res.send('Uploaded: ' + req.files.image.name)
return next()
});
app.listen(3000);
console.log('Express app started on port 3000');
Here is a good Tutorial | Upload Image using Node.js
Happy Helping!
You have set multipart/form-data for uploading files, but none of the middleware you have enabled support that content-type. Normally you'd use a middleware like multiparty or busboy to parse multipart request data like your image.
I created a express 3 app with the express generator and installed socket.io.
On app.js im emiting a message:
io.sockets.on('connection', function(socket) {
socket.emit('init', { msg: 'Welcome'});
});
At server side I wrote:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
<script src='/socket.io/socket.io.js' />
<script>
var socket = io.connect('http://127.0.0.1:3000');
socket.on('init', function (data) {
console.log(data.msg);
});
</script>
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>
If I run app.js It should print "Welcome" on the console, but its not priting anything. I checked if /socket.io/socket.io.js is accesed and it does.
When running the app I get:
info - socket.io started
Express server listening on port 3000
GET / 200 28ms - 472
GET /stylesheets/style.css 200 163ms - 110
debug - served static content /socket.io.js
Am I missing something? I followed the socket.io webpage examples, but it seems that server is running fine... maybe something at the client-side?
EDIT: I also tried var socket = io.connect('http://127.0.0.1', { port: 3000 } ); on the client side, and also running all socket client side from the body.
Doing a console.log on the io.sockets.on event gave nothing... so "connection" is never reached.
app.js:
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
var server = http.createServer(app)
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
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')));
});
app.get('/', routes.index);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
var io = require("socket.io").listen(server)
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
});
index.html:
<script>
var socket = io.connect();
socket.on('news', function (data) {
console.log(data);
});
</script>
In your browser's console you should see an object containing "hello": "world".
adding a index.jade file to the example I posted before
server.js
var app = require('express')()
, http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server)
server.listen(3000)
io.set('loglevel',10) // set log level to get all debug messages
io.on('connection',function(socket){
socket.emit('init',{msg:"test"})
})
app.get('/',function(req,res){
res.render('index.jade')
})
/views/index.jade
doctype html
html
head
script(src="/socket.io/socket.io.js")
script.
var sockets = io.connect()
sockets.on('init',function(msg){
alert(msg.msg)
})