Render EJS and save it to Redis - node.js

In my Node-Express app I'm using Postgre as main data and Redis as cache system.
When a visitor request an url, my app request the json to Redis. If isn't available, make a request to Postgre, save the json to Redis and then render the EJS template. The next request to the same url, I get the json from Redis and render the template.
Now I want to save to Redis the full rendered template instead of json to save CPU usage. I tried this trick but it did not work:
Render ejs file in node.js
Any ideas or suggestions how to do it ??
Thanks in advance for your help.

The Express API reference shows that res.render() accepts a callback as the last argument. That callback is called with (err, html), so just pass in a callback and store the (string) html into redis.

Related

how to render a file and send data to page in the same GET request

I am using angularjs on client-side and experss.js in server-side , i want to render a page and send data to the page (to fill a table) in the same get request
i tried using ejs engine to fill the table in the server-side and then render the page , but the problem with this solution is that the client-side (angularjs) cant access or manipulate the data.
other solution is (atrivial one) is to
make get request to get the page on cient-side
render the page on server-side
make another get request from client-side to get the data
send the data from server to client
The problem with this is that it contains two get requests.
Is there a possible way to render the page and send the data in one get request?
I am doing this to make the loading on site more efficient. Can i acheive more efficiency with one GET request ?
No, you can't. You can only have a single response to a given request. The browser is either expecting an HTML document or it is expecting JSON, it doesn't make sense to give it both at once. but you could render the page and send the data at the same time:
res.render('reports',{data:json});
and then access those data in the newly rendered page.
alternatively you could send a flag when making the call , and then decide whether you want to render or send based on this flag.
Or Ideally, it needs to be 2 separate route, one spitting json and other rendering a view. Else, you could pass a url param, depending on which you return json or render a view.
router.get('/reports/json', function(req,res){
var data = JSON_OBJECT;
res.send(data);
});
router.get('/reports', function(req,res){
var data = JSON_OBJECT;
res.render('path-to-view-file', data);
});
To access data in an AngularJS app without a second server request, include a .value script:
<script>
angular.module("myApp").value("myData",
<JSON data here>
}
</script>
Then in the controller, inject it:
app.controller("myCtrl", function($scope, myData) {
$scope.data = myData;
})
For more information, see
AngularJS angular.module API Reference - .value method
Could you please try using rout.getparam and pass values in route in the get request

How do I run a node.js function from an html page without using ajax/using express?

I have been having trouble with ajax, and I just want my html to pass a function when a button is passed, but that function is in a node.js file.
How could I do this without AJAX, and if AJAX is required, could I be linked code?
Create index.js file and attach it to your html (index.html) file.
Then in html file if you are submitting form then pass onClick=functionName() as attribute in <form> tag.
In index.js file, you can add functionName function and that function works as your frontend function.
Use axios or inbuild request to fetch data from that function via endpoint.

Passing Data from Node-Express backend to Vue component

I'm still learning Vue.js 2 so I do apologize if this question is a bit silly. I'm building an application using MongoDB, Node, Express and Vue. Normally I'd use a template engine such as Ejs where data passed through Express's res.render method can be readily captured in the template.
Is there a similar way to pass data from backend to the root Vue component? For example, normally, a get request fetches some data from Mongodb, express will render the template file and pass data to it.
app.get("/gallery/:id", function(res, req) {
var id = req.params.id;
database.findById(id, function(err, data) {
....
res.render("home", data);
}
});
Now my root Vue application is attached to html file. I'd like to be able to dynamically render the app with data returned from the database.
I've built an app before that streams data from an api and passed it to my Vue component via socket but I feel like using a socket in this case is unnecessary.
Use http. What's the problem? You can use XmlHttp, or a lot of folk seem to be using Axios. Trigger the call in the onload of your page, or use one of the vue lifecycle hooks. The very good vue docs don't have much to say about how and when to do this. We do it in the onload of the page, and we instantiate vue when the request for page data returns.
The question has already been answered, but I wanted to share my approach. I've been experimenting with rendering an object server side using res.render(), putting it in a div where display: none, and then grabbing the object on the client and passing it to Vue's data attribute.

How can I send information from NodeJS server to client side?

For example, I want to signal to the client side that a username sent via the POST method in an HTML form already exists in my database.
I know how to recuperate POST data with body-parser and I know how to look it up in a MySQL database.
I know that I could use Ajax to write an error message directly on the form. What does my NodeJS server need to send and how does it send this information?
I've searched through numerous tutorials and I just found solutions where they send a new HTML page. I want to keep my web page the same and use functions like appendChild() to post the error message.
There are a couple of ways you could send data from server-side, so NodeJS, to client-side - which I assume in your case would be some JavaScript file like main.js that handles DOM manimulation.
So, the 1st way you could send data is through a templating engine like Handlebars, for example. There is an easy to use module for express you could get here: hbs.
Now to quickly summarize how an engine like that works, we are basically sending an HTML file like you probably saw in the tutorials, however, a templating engine like Handlebars allows us to send actual data with that file dynamically, so what we would do is render a specific Handlebars template (which in core is just HTML), and pass in a JavaScript object to the render call which would contain all the data you want to pass into that file and then access it in the .hbs file.
So on the server-side, we would write something like this, assuming we have a file called home.hbs and set up Handlebars as the templating engine:
router.get('/home', function(req,res) {
var dataToSendObj = {'title': 'Your Website Title', 'message': 'Hello'};
res.render('home',dataToSendObj);
});
And access in home.hbs like this:
<html>
<header>
{{title}}
</header>
<body>
message from server: {{message}}
</body>
</html>
Now, the issue with this approach is that if you wanted to update the data on the page dynamically, without having to reload the page, using a templating engine would not be ideal. Instead, like you said, you would use AJAX.
So, the 2nd way you could send data from your NodeJS server to the front-end of your website, is using an asynchronous AJAX call.
First, add a route to whatever route handler you are using for AJAX to make a call to. This where you have some logic to perhaps access the database, make some checks and return some useful information back to client.
router.get('/path/for/ajax/call', function(req,res) {
// make some calls to database, fetch some data, information, check state, etc...
var dataToSendToClient = {'message': 'error message from server'};
// convert whatever we want to send (preferably should be an object) to JSON
var JSONdata = JSON.stringify(dataToSendToClient);
res.send(JSONdata);
});
Assuming you have some file such as main.js, create an AJAX request with callbacks to listen to certain event responses like this:
var req = new XMLHttpRequest();
var url = '/path/for/ajax/call';
req.open('GET',url,true); // set this to POST if you would like
req.addEventListener('load',onLoad);
req.addEventListener('error',onError);
req.send();
function onLoad() {
var response = this.responseText;
var parsedResponse = JSON.parse(response);
// access your data newly received data here and update your DOM with appendChild(), findElementById(), etc...
var messageToDisplay = parsedResponse['message'];
// append child (with text value of messageToDisplay for instance) here or do some more stuff
}
function onError() {
// handle error here, print message perhaps
console.log('error receiving async AJAX call');
}
To summarize the above approach using AJAX, this would be the flow of the interaction:
Action is triggered on client-side (like button pressed)
The event handler for that creates a new AJAX request, sets up the callback so it knows what to do when the response comes back from the server, and sends the request
The GET or POST request sent is caught by our route handler on the server
Server side logic is executed to get data from database, state, etc...
The new data is fetched, placed into a JSON object, and sent back by the server
The client AJAX's event listener for either load or error catches the response and executes the callback
In the case of a successful response load, we parse the response, and update the client-side UI
Hope this is helpful!

Node.js works with CouchDB and Backbone.js, How json is being served?

I am trying to build a test app for learning Node.js. I came from wordpress background and Apache has setup most of backend logics for me. But now, I have to build my own. I have a question about how to serve JSON files from server side to client side. What is the workflow -- Backbone.js handle all client side Data manipulation, send/save/get/fetch from couchDB, serve JSON object from NODE.js backend?
I am using Express Microframework for building HTTP server, installed the Cradle middleware for access CouchDB NoSQL database. I successfully posted the data from Client side HTML (Jade template engine) to the CouchDB Database/Document and able to retrieve those data back from Server through Cradle middleware. Things work out great. But it was all done by Backend.
I want to use Backbone.js for my client side Javascript. Backbone.js is looking for JSON object which send back from the HTTP server. Cradle Middleware is able to create JSON object but only send them directly to the Jade Template, I could use Jade syntax for loop to iterate over the data object but it still not meet what I want for Backbone.js handle all the data entry. I realize that I need to get JSON obj via ajax ( either a file generated by HTTP then send back to the client OR send straight object to the client ). Cradle Middleware could not do that.
I did more research on this questions. I tried CouchApp, it does what I need. Using the Backbone.js to handling all the data, send/save/fetch data from CouchDB database. But it is a running in CouchApp, it is not an Express Node.js workflow. ( Maybe I am wrong or just do not how it work )
I tried backbone-couchdb.js. I read through the Details and still do not know it is going to help me to get what I want. ( Maybe need more tutorial or code example ). I am still thinking that I need a Backbone CouchDB driver to connect those two and somehow serving them by NODE.js backend.
Is there anybody who could tell me about how JSON file is being served by Node.js, how backbone.js interact with data save/fetch/get from CouchDB? What is the best practice / workflow? Other good resources, code examples, useful tools?
Cradle Middleware is able to create JSON object but only send them directly to the Jade Template
This is incorrect. You can just send the json back without rendering a template.
function(req, res, next){
db.view('user/byUsername', { key: 'luke' }, function (err, doc) {
res.send(doc); // or res.json(doc);
});
}

Resources