I need to send a warning message from express to the browser.
So, I need help to do it. Currently I am working with a MEAN app.
Here, I have to communicate between Express and HTML.
I will give you an example using express and .ejs as a view engine. It gives more flexibity than plain .html but is still simple (and looks nearly identical).
This way you can setup your routing (the way you redirect users to different sites based on address/path) and at the same time pass data to your views.
router.js
var express = require('express');
var router = express.Router();
router.get('/', function (req, res, next) {
res.render('someView', {msg: 'Express'});
});
Above will pass a variable called msg with value Express and render yourView (basically some of your pages).
yourView.ejs
<!DOCTYPE html>
<html>
<head>
<title><%= msg %></title> // here is how you can use variable passed from back-end in .ejs templates
</head>
<body>
<h1>Hello there</h1>
</body>
</html>
Of course you can pass arrays, json, obj etc. to your view.
router2.js
var arr = ['a', 'b', 'c'];
var obj = {a: 1, b: 1, c: 2, d: 3, e: 5};
var objJSON = JSON.stringify(obj);
res.render('demo', {arr: arr, objJSON: objJSON}); // key: value, so you will refer by key in your view
You could also use this values in view's JS scripts.
For example like this
// html/ejs markup here
<body>
// bla bla...
<script>
var tmp = <%= msg %>
alert(tmp);
/* obviously you need some kind of logic when you want
alert/popup or whatever to happen. At least some simple IF statement.
*/
</script>
</body>
</html>
However more popular way to display messages to end-users in express is using flash messages. Check out this link to Connect-Flash middleware. Simple usage is exapl
See the docs of express and read about response. Example:
app.get('/user/:id', function(req, res){
res.send('user ' + req.params.id); // Send to view (html,jade, ejs) somethink message
});
The res object represents the HTTP response that an Express app sends
when it gets an HTTP request.
There are more responses methods, as res.sendFile, res.render, res.redirect, etc.
Related
i have gone back to basics to try and create a simple example of calling a REST API, receiving some JSON back and rendering the JSON data in HTML using Jade.
I have tried many approaches to this but cannot get any to work.
what code would i need to add to my main script file (below - lxrclient.js) to achieve this. I know i need to add express module, and render the view, but no matter who may approaches i have tried i cannot get it to work. I have also added the jade file i am using further down. really appreciate any help anyone can provide with this.
//this is my main script file lxrclient3.js
var http = require('http');
var express = require('express');
var app = express();
app.set('view engine', 'jade');
var options = {
host: '41.193.214.130',
port: 2510,
path: '/eiftidemo/clt_list',
method: 'GET'
};
http.request(options, function(res) {
var body = '';
//node of these statemnst excecute
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var clientsData = JSON.parse(body);
debugger;
});
}).end();
app.get("/clientlist", function(req, res){
res.render('listlxr', {clientd: clientsData});
});
var server = app.listen(3000, function() {
console.log('Our App is running at http://localhost:3000');
});
here is my Jade view
html
head
title List of Clients
link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css")
body
div.row
div.col-md-3
div.col-md-6
div.panel.panel-primary
div.panel-heading.text-center
h1 Client List for Hyposure
div.panel-body
table.table
each clients in clientsData
tr
td.media
span.bg-info= clients.clientName
td.media
span.bg-info= clients.clientSurname
thx to anyone who can help
First of all, when you say Jade I hope you mean Pug, if not, you should update to the newest version of Pug instead.
Now, to send data to your template for the engine to render you send a JSON object, like so;
res.get("/", function(req, res)
{
res.render("page.html", {greet : "Hello"});
}
This is a standard way of rendering a page and sending some data along side.
Now in your Pug (Jade (Same thing)) template you can access the sent variable like so;
html
head
title List of Clients
body
h1 #{greet} <!-- This will print "Hello" -->
This should give you a basic idea on how to render data onto a site, you can also send nested objects and you just work it the same way as in this example, but you point to the correct key. So for example if you're sending the following object:
{
greet: {
message : "Hello",
who : "Adrian"
}
}
Then you can print values from that using:
#{greet.message} #{greet.who}
A bit about my background: I haven't done much web development for a while, and am only recently starting to get back in the swing of things. I remember the days when I used to have static header/footer files in PHP, and code like so:
<html>
<head>
<title>Title</title>
</head>
<body>
<?php include("header.php") ?>
Body text here
<?php include("footer.php") ?>
</body>
</html>
I'm currently making the switch to Node for my backend (for various reasons not pertinent to this post). I'm still quite new at this, so I'm wondering if there is a simple way to go about having static headers/footers (which contains navbars and such) for my front end. I'm trying to use Bootstrap for my front end framework.
I think using Jade, or other template engines, might be one way to go about doing this, though I'm not necessarily sure if I want to use Jade just yet as dealing with js and HTML is troublesome enough without adding another pseudo-language/format/template into the mix. So I'm wondering if there is a solution that does not use template engines.
Here's what I currently have for my app.js/web.js file:
var express = require('express')
var app = express()
var path = require('path')
var fs = require('fs');
var bodyparser = require('body-parser')
app.use(bodyparser.urlencoded({extended: false}))
app.use(express.static(path.join(__dirname)));
app.get('/submit', function(req,res) {
[functions omitted for brevity]
})
[other processes omitted for brevity]
app.listen(8080)
Thank you!
I would highly recommend to use a view engine for this. Node is not like PHP. PHP scripts are processed sequentially and the rendered output is sent as the response. If you were to do the same approach in node you would be building a string in JavaScript and then sending it out to the client.
app.get('/submit', function(req,res) {
var output = '<html>';
output += '<head>';
...
res.send(output);
});
Now imagine that you have to query a database:
app.get('/submit', function(req,res) {
var output = '<html>';
output += '<head>';
...
db.query(query, function(err, result) {
output += 'the result is ' + result;
...
res.send(output);
});
});
So the lesson is, use a templating engine as they are designed for building the html output for you. Start with ejs as it will have a more familiar syntax to php.
I am trying to parse some json with Handlebars on my website. I don't get any errors but also don't get any content. I've developed my own rest point to return a json response and I think my problem might be there somewhere, but you can see the response in the code.
http://codepen.io/anon/pen/Czdxh
$(document).ready(function(){
var raw_template = $('#post-template').html();
// Compile that into an handlebars template
var template = Handlebars.compile(raw_template);
// Retrieve the placeHolder where the Posts will be displayed
var placeHolder = $("#all-posts");
// Fetch all Blog Posts data from server in JSON
$.getJSON("https://instapi-motleydev.rhcloud.com/liked",function(data){
$.each(data,function(index,element){
// Generate the HTML for each post
var html = template(element);
// Render the posts into the page
placeHolder.append(html);
});
});
});
Thanks for any help!
The problem was I was getting an array response from the server and needed to adapt my template to include the {#each this} syntax. Also switched my getJSON to a simple get and looped over the reaction that way and tossed the $.each handler.
I have a pretty heavyweight query on the server that results in a new page render, and I'd like to pass along some of the results of the query to the client (as a javascript array of objects). This is basically so I don't have to do a separate JSON query later to get the same content (which is mostly static). The data will be useful eventually, but not initially so I didn't put it directly into the document.
app.get('/expensiveCall', function(req, res) {
// do expensive call
var data = veryExpensiveFunction();
res.render('expensiveCall.jade', {
locals: {
data: data,
}
});
});
});
data is a array of objects and only some are initially used. I'd like to pass either the entirety of data over or some subsets (depending on the situation). My jade looks like normal jade, but I would like to include something like
<script type="text/javascript">
var data = #{data};
</script>
but this doesn't work (it's an array of objects).
You can't inline a JS object like that, but you can JSON.stringify it before:
<script type="text/javascript">
var data = !{JSON.stringify(data)};
</script>
In a php file I can do:
<p><?php echo "hello!";?></p>
Is there a way to do this in node, if yes what's the logic for it?
I have an idea how could this be done:
Use an identifier markup for node in the HTML file like: <node>code</node>
Load & Parse HTML file in Node
Grab node markup from the HTML file and run it
But I'm not sure if this is the best way or even if it works :)
Please note I want to learn node.js, so express and other libraries and modules are not answers for me, because I want to know the logic of the process.
What your describing / asking for a node.js preprocessor. It does exist but it's considered harmful.
A better solution would be to use views used in express. Take a look at the screencasts.
If you must do everything from scratch then you can write a micro templating engine.
function render(_view, data) {
var view = render.views[view];
for (var key in data) {
var value = data[key];
view.replace("{{" + key + "}}", value);
}
return view;
}
render.views = {
"someView": "<p>{{foo}}</p>"
};
http.createServer(function(req, res) {
res.end(render("someView", {
"foo": "bar"
}));
});
There are good reasons why mixing php/asp/js code directly with HTML is bad. It does not promote seperation of concerns and leads to spaghetti code. The standard method these days is templating engines like the one above.
Want to learn more about micro templating? Read the article by J. Resig.
You can try using JooDee, a node webserver which allows you to embed serverside javascript in your web pages. If you are familiar with Node and PHP/ASP, it is a breeze to create pages. Here's a sample of what a page looks like below:
<!DOCTYPE html>
<html>
<: //server side code in here
var os = require('os');
var hostname = os.hostname();
:>
<body>
<div>Your hostname is <::hostname:></div>
</body>
</html>
Using JooDee also lets you expose server javascript vars to the client with no effort by attaching attributes to the 'Client' object server side, and accessing the generated 'Client' object in your client side javascript.
https://github.com/BigIroh/JooDee
Use a template engine. From terminal
npm install ejs
In code:
var ejs = require('ejs');
var options = {
locals: {
foo: function() { return "bar"; }
}
};
var template = "<p><%= foo() %></p>";
console.log(ejs.render(template, options));