Passing data to dynamic page in node.js without templating engine - node.js

I am building a blogging website with node/express.js and mongodb. Now, I want to view individual blog so I created an endpoint of '/articles/:id' so I can only display that particular blog details.
But the problem is how do I show the blog related information in an html page, how do I send that information to frontend ? Like I can't even do a fetch on the '/articles/:id' endpoint because the id would change depending on the specific blog.
One solution you might say is that to use a templating engine but I build the whole thing up till now without templating engine and also I want to know how to do it without a templating engine.
This is my code for individual article. Here I am fetching the blog data from mongodb database and sending it via res.json
app.get('/articles/:id', (req, res) => {
ArticleModel.findById(req.params.id).then(article => res.json(article));
});
Is it possible to so without any templating engine at first place ?

In my view You have two alternatives :-
-> you can send HTML code using res.send like this.
app.get('/articles/:id', (req, res) => {
const city="Londan";
const country="England";
const temp=24;
res.send("<h1>Hello, The temperature in "+city+","+country+" is "+temp+"</h1>");
});
-> Use a library which replaces template engine or in other words which t can do HTML and DOM manipulation like jsdom, cheerio, plates.(haven't tried this personally) because I have always use template engine because it helps me to separate service side code and client side code.
This answer talks in more details about https://stackoverflow.com/a/10114041/13126651.
But my recommendations would be to use template engine for it will simplify your most of the work, there are lof of great options like ejs and my personal favourite is handlebars.

Related

Is it possible to render handlebars templates from a database on node.js?

I'm looking to create a single node.js application that will render multiple different client websites.
We currently run one node.js application per client website, but I think this might be overkill as the serverside logic is exactly the same for all of them, the only difference being the handlebars template.
I'm looking to re-architecture to have a single node.js application which will then render the different client's websites based on some incoming information, will use nginx to add a header or something to the request so the app knows which website to render.
Is it possible to store the handlebars template within a database and then request the template at render time? Rendering a simple single page should be easy enough, but I'm struggling to understand how partials would be rendered?
Looking to achieve something similar to Shopify's Storefront Renderer, not sure if it's possible to do with handlebars or if it's better to use of of the LiquidJs ports for Node to achieve this?
https://shopify.engineering/how-shopify-reduced-storefront-response-times-rewrite
I do this with different countries, same concept as you with different Clients.
You just create the Handlebars layout and put it in your partials folder. No need to put template in your database.
Then your server logic will have eg clientName, and your Handlebars will have IfEqual tags (you'll need an IfEqual helper)
Example:
Server route will give a variable clientName.
Handlebars you have the main view page with only the IfEqual helpers.
{{#ifEqual clientName 'Client Name 1'}}
{{> client/clientName1}}
{{/ifEqual}}
{{#ifEqual clientName 'Client Name 2'}}
{{> client/clientName2}}
{{/ifEqual}}
Your helper function will be
, helpers: {
ifEqual: function(x, y, options) {
return(x == y) ? options.fn(this) : options.inverse(this)
} // {{#ifEqual statusLogin 'unconfirmed'}} {{/ifEqual}}
Search nodejs handlebar helper if you dont know how to set it.
So my partial folder, you can create a folder in it called client, and put all your Handlebars template in there. Search for nodejs handlebars partial folder setup if you dont know how to do it.
The handlebar helper function I found it I think in stack overflow, so you can search for others if you want, but for me it works.
Your partial template files just do as normal Handlebar files.
So the main idea is User loads the page, depending on what Client flag you put it, it loads up that template.

Looking for passportjs-local simple example using MEAN only

I am looking for a very simple example for using Passportjs (Local api) in my MEAN application. I took a reference from one example on github. There they have used jade to render the page after authentication. But I just want to use my home.html to show home page after authentication.
I have searched many example but in all they are using either jade or ejs. I don't want to use any engine to render the home page.
If anyone can provide a very simple example just using MEAN that would be a great help.
I don't want to use jade or ejs. Just simple html to render page.
Just setup a route similar to this:
app.route("/login")
.post(passport.authenticate("local"), function (req, res) {
res.json(req.user);
});
Then call that as an post call from the function you bind the form to in angular, you don't need to use jade/pug/ejs or any of it. You can simply use express as an API server. Just have angular redirect to the route you want after the successful return of the authentication (you should get a user object back)

How to create href links in a view, pointing to Express routes?

I want to create href links inside my views, but I do not want to point to a static address. I want to dynamically create href urls based on routes.
Example:
// app.js:
app.get('/test', function testPage(req, res, next) {
// do something here
});
// inside view.html:
<a href="path('testPage')" /> // something similar
<a href="/test" /> I do NOT want this!
Am I missing something, or there is no way to do that easily?
I've searched and I found that app._router.stack has all routes. But they are just a plain ARRAY so they don't have any kind of id or smth! What I came up with, is a function that parses all routes (from stack), gets their name, which is set only if the function has a name (http://expressjs.com/4x/api.html#req.route) and then create an object with key (route name) -> path.
Then I can use this function (somehow) inside views to create paths, right?
Any better ideas?
Coming from PHP frameworks background, I am used to two way routes. However, from what I've seen in tutorials, people just use the static links. I think it has to do with the nature of Node.js web applications. Lots of them are SPAs, so you just build an API and then refer to it statically from the frontend application.
When researching this topic, I've came accross this little library called 2-way router which can be used with Express. I haven't experimented with it yet, but it might be useful to you.
EDIT: Tried to re-word my search and I've found similar thread about url generation and express route naming.
EDIT: You can also implement django-like routing.

Express - Create a new view engine

I know that expressjs supports many view engines, like: ejs, jade, etc. I saw a list here: http://expressjs-book.com/forums/topic/how-to-use-alternative-non-jade-template-engines-with-express/.
My question is how can I create my own view engine. I've looked in ejs and in other engines' source-code but I didn't really find an expressjs documentation on how to create a new engine, what are the requirements, or a tutorial about it.
Is it possible to create a new custom view engine? Thanks.
Yes, of course. Take a look at this list for templating engines.
Regarding express itself, what you need to do is create a plugin, or even a middleware function - that will attach your render, renderFile and similar methods to the response object.
If you don't use an express engine and try to, say, response.render('index.ejs');, you'll get an error. But if that response object has a render method, you're fine. So it boils down to extending expresses' response object with what you need.

Can I write middleware to affect the data that is being sent to my template renderer?

I'm writing a web application based on Node.js and Express, using Dust for my templates. My Dust templates all use the same master layout in a separate file. Right now a simple route handler in my app looks like this:
app.get('/', function (req, res) {
res.render('index', {
tenant: req.tenant
});
});
The tenant is being used for rendering some parts of the master layout. Now, I feel like it's pretty inefficient (devtime-wise) to add the 'tenant' variable to the view model in every route handler. In ASP.NET MVC I would write an action filter that runs after every action and adds the tenant to the view model. Is there something similar I can do in Express? Write some connect or router middleware? Or does res.render perform the rendering immediately without any possibility to modify the view model lateron?
And two minutes after posting the message, a nice chap on IRC gives me the answer.
res.locals.tenant = <tenant>
in the middleware does the job.

Resources