How to use Backbone with Jade correctly - node.js

Hi I´m developing a expressjs backbonejs with mongoose, my template engine is HTML (with text.js).
My app have a navbar with Register and Login links and a container where I put contents. I implemented a login system with passportjs, it works well, when you are logged in you´ll have a req.user object with your user info.
Now I´m blocked cause I´d like to hide the navbar links if I´m logged in.
When I did the POST to /login if all is success, i redirect to /account and load another view with it template, I´ll have the req.user data but the navbar view doesn´t have it and then I can´t hide the links.
I tried to pass to jade cause I can put the HTML code of the navbar in a template and after POST /login render a jade template that contains the navbar template with "extends". But in this cause I lost all my Backbone functionality cause I can´t navigate with # in the URL.
Wich is the correct way to do this?
Hope you understand me, regards.

You may solve the situation by using singleton pattern. I.e. a global config object which has a method isLogged for example. The idea is to initialize this object in the entry point of your application. The place where you have the needed data and later access it via that singleton. For example:
var AppConfig = (function() {
var isLoggedFlag = false;
var changeLoggedStatus = function(value) {
isLoggedFlag = value;
}
var isLogged = function() {
return isLoggedFlag;
}
return {
isLogged: isLogged,
changeLoggedStatus: changeLoggedStatus
}
})();
When you know that the user is logged just use:
AppConfig.changeLoggedStatus(true);
In your view just check
if(!AppConfig.isLogged()) {
// hide whatever you need to
}

Related

MongoDB, Node, Express, EJS - Pass a array/variable from backend to frontend (from route to client)

I've been trying to figure out a better way to push a variable from the backend to the frontend. Right now I do something like this.
I have a MVC-pattern, so when hitting the route
app.get('/fil', middleWare.isLoggedIn, user.fil)
... trough node does some querying the DB, and pass on the data.
exports.fil = async (req, res) => {
try {
faktura = await Lan.find().populate('client', 'namn kundnr')
res.status(200).render('pages/createInvoice', {
faktura: faktura
});
} catch (err) {
return res.status(500).send({
message: err.message || "Some error occurred while retrieving datas."
});
};
};
... it generates the page, with the help of EJS (i love EJS) and then pass it on to the client/user.
And in the .ejs-file that is served to the client/user I add the following
<script>
var fakturor = <%- JSON.stringify(faktura) %>;
</script>
which then means that I use up the variable and work with it with JS.
And this is where my question pops up. Is this a good way to do it or is there any other way to handle it?
I guess one idea is to let the user to query the DB straight from the page, but in my case I believe it wouldn't actually be better for the user to do so (the user will reieve like 100 different rows that they will be able to filter and then download a file of)
But is there any other ways I could do this without the script-tag? Like i said, I guess a ajax-call from JS/the client could be used but could you do it any other way? Can EJS do it any other way?
ejs is used for static pages mainly, if you want to build a dynamic page I would look for a single page application framework like angular and react.
if you still want to use ejs you can use ajax call to the server to load a variable from the DB.
I would never query directly from Front end to DB because then you are not controlling the security of the server, always go through the BE.
also try to think if you really need a variable in the front end, can you solve your problem using rendering only?

Redirect If Authenticated NodeJS

I am using the following tech
NodeJS
ExpressJS
VueJS
ngnix
i store the x-access-token in the localstorage.
When the user visits the site www.example.com a vuejs component does the following
Verifies if the user is logged in by calling an authentication endpoint
If verified, it redirects to www.example.com/controlpanel
Ofcourse the problem is it takes a while for the vuejs component to load and therefore the page loads and later is redirected.
Is there a way of handling the above scenario in a cleaner way. Using ngnix even?
Thanks
In the component which is rendered on the visit to homepage(root route /)
add a beforeRouteEnter() navigation guard as follows:
//in root route component options
beforeRouteEnter(to, from, next){
myAjax.get('/auth').then((res) => {
if(res.data.user){
//user logged in
next('/controlpanel');
}else{
next('/');
}
});
}
this guard is called before the route component is rendered and only gets confirmed and rendered if you invoke next()
keep in mind you will not have access to the compnents's vue instance as the component is not created yet
to get acceess to t vue instance inside beforeRouteEnter() do this:
beforeRouteEnter(to, from, next){
next(vm => {
//acess the component's instance using vm
}
}
For more info check out In-Component Guards

Don't redirect on POST express.js

I'm making a basic web app with Node.js and Express 4 and I'm trying to implement a "follow" function. I did some inspecting on the Github website and noticed it used a form with a follow button that would post to the server to follow a user. I think this sounds like a good approach but when I post I don't want to have to reload the page just like the github website.
How does one this inside of Express 4? Everything I put inside the .post route always end up in a page load. I'm pretty sure in jQuery's ajax method you can just return false and nothing will happen to the page, just the request will be sent which is what I want to happen because I'm using a RESTful api and I want to add the user to the current user's following but I don't want to have to use jQuery just for this function. I would prefer it be done in Express if possible, though any help would be appreciated.
views/user.handlebars
<h1>{{user.displayName}}</h1>
<p>#{{user.username}}</p>
<form action="" data-userid="{{user._id}}" method="post">
<button name="follow" type="submit">Follow</button>
</form>
routes/users.js
app.route('/:username')
.get(function(req, res) {
// get :username user from api and load info
...
})
.post(function(req, res) {
// don't reload page
???
// send PUT :username user to current users following array
...
});
So you're on the right track, but instead of putting your actions in the HTML (in your jade file) you're gonna have to add a script section to your jade and use javascript to attach an onClick event to the button so that when you press the button you invoke your ajax method.
Let me know if that doesn't make sense.

Sails.js - use login instead of id for REST api

I'm using Sails.js framework, and I have User model with login field.
I also have User controller that allows me to send request like
http://localhost:1337/user/:id
And it returns given user data. However I'd prefer to use user login instead of user id so I could use /user/mylogin instead of /user/564a0aacecf0e8fb20c38a4e. Is there any way to do it without creating routes myself (I like how sails handle all default routes including relations like /user/:id/comments and I dont want to rebuild all of those just to use login instead of id)
You could do /user?login=username. This is handled by sails's blueprint api: http://sailsjs.org/documentation/reference/blueprint-api/find-where
If you really want it you can have it. But you have to get your hands a bit dirty. There are a few possibe ways. But I am pointing you out the easiest way seemed to me.
Add a route like following in your config/routes.js.
'/user/:myLogin': {
controller: 'user',
action:'getUserByUserLogin'
}
Add an action named getUserByUserLogin in your
api/controller/UserController.js. You can access the myLogin
value from request object from the controller action with
req.param("myLogin").
module.exports = {
getUserByUserLogin: function(req, res){
var myLogin = req.param("myLogin");
/* Do whatever you want */
}
};

Use dynamic express routes within another Express route

For a school project, I created a plugin system for an Express.js-Application in Node.js. The main page of the application should display a dashboard, where every root page of each plugin should be displayed in a div. Every root page is accessible over the pluginName/-route.
What I would like to do is the following: I wanna include the HTML-string of every home-route in the dashboard. But for this, I need to call the routes inside Node.js (like partials) and for some plugins I even have to provide some properties.
Does someone have an idea, how this could be implemented?
e.g. I have following route:
router.get('/pluginName', function(req, res) {
res.render(__dirname + '/views/home.handlebars', {
layout: __dirname + '/views/layouts/main.handlebars',
markup: markup // Pass rendered react markup
});
});
Now I want to pass the resulting HTML from this route into another route.
So far I had the following ideas:
Simply add the URLs of the plugins to a "data-ajax-url" attribute of the divs and load the stuff via AJAX.
Make an HTTP-Call to every route and append the result on server side (pretty nasty...).
Create a renderDashboard-function for every plugin, where I get the HTML using app.render(...) and then I append the result.
But I'm not really sure, which approach (if any) would be the nicest.

Resources