I am using webmatrix and building node.js application. In that i want to pass the value from the node.js to the HTMLPage in the project.
var http = require('http'); var URL = require('url');
http.createServer(function (req, res)
{
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('Hi man');
}).listen(process.env.PORT || 8080);
With that code i tried it gives a page with hi man.Its obvious.But i want this to be rendered in the html page i am having in the project. How to achieve tat. Please give some suggestion on this..
First I recommend you use Expressjs, which is a framework for Nodejs.
Then I recommend you use EJS, an engine template for Nodejs.
When integreses all, you can use code similar to:
...
app.set('views', __dirname + '/views');
app.register('.html', require('ejs'));
app.set('view engine', 'html');
app.use(express.static(__dirname + '/public'));
app.use(express.favicon(__dirname + '/public/img/favicon.ico', { maxAge: 2592000000 }));
app.use(expressValidator);
...
And
...
app.get('/test', function(req, res){
res.render('test', {msg: "Hello World"});
});
...
Finally in your file views/test.html:
...
<div><%- msg %></div>
...
I hope it helps somewhat.
Additionally review:
Greetings.
Sounds like you want to request your nodejs server using AJAX and inject the server's response into an HTML element.
Check out: http://api.jquery.com/jQuery.getJSON/
Here's an example using jQuery to connect and retrieve the server response from node running on port 8080 of different host, and insert that into an HTML element.
node:
var http = require('http');
var url = require('url');
http.createServer(function (req, res)
{
//parse the url and query string from the request
var url_parts = url.parse(req.url, true);
//if the callback query parameter is set, we return the string (or object)
if(url_parts.query.callback){
var str = "Hi man";
res.writeHead(200, {'Content-Type':'text/html'});
res.end(url_parsed.query.callback+'("'+str+'")');
//if it's not set, let's return a 404 error
}else{
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('404 Error');
}
}).listen(process.env.PORT || 8080);
index.html
<div id="my-div"></div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
//getJSON and the callback paramater make us cross-domain capable.
$.getJSON('http://myotherhost.com:8080/?callback=?', function(data){
$("#my-div").html(data);
});
});
</script>