Website Architecture for Node, Backbone+Marionette, Mongo DB GridFS - node.js

I am programming a website with a node.js and mongodb grifs on back-end with backbone and marionette as front end frameworks.
As I am new to creating single page applications (SPA) I may be wrong in any of my assumptions, please correct me wherever I am wrong.
The way I understand the flow of control is:
As soon as the first request to the server is made to abcxyz.com, nodejs server serves the base html file via a get request from the server.js file. This html file links to the main.js file which holds all the backbone+marionette models, collections and views.
As my aim is to write a SPA (single page application), I assume that from here onwards the flow of control remains completely within the main.js file as it is the file which handles the url routing (think of #routes for emails in gmail).
Now my question is this: How can I carry data to and from the mongodb gridfs database for each route change in backbone. Putting another way - how does backbone interface with mongo database which can be accessed only in the server.js file, and how do I communicate a change of route (hence a change in the data needed for backbone views) from backbone to the node.js server?
I'm sorry for a really long question, feeling very confused :(

Related

How to correctly use Nodejs and backbonejs together?

I have an application which uses nodejs as server and backbonejs as the frontend framework. As I know, both backbonejs and nodejs handle the url.
I have a question: for example, let say I have page called localhost/project and a page called localhost/details. When I load either of these pages, nodejs server should be called first, and then in the view.jade I have:
script(type="text/javascript", data-main="/js/bootstrap", src="/js/lib/requirejs/require-min.js")
which initiate the control of backbonejs. So, does that mean everytime that I load a NEW page (localhost/details --> localhost/project), I have to reload all the steps for initializing the backbonejs (requireJS work)?
Unless you have to do it differently, perhaps a better approach would be to use node.js as a REST API. I would use a framework like express. Then, in your Backbone code, hook your model and routes up to call your node API and update the views with the data it receives.
Unless you are doing any kind of processing on the server side, you can skip the node step and run your SPA's right off of Firebase or Parse.

Is there a way to load partial views from server side when using angular?

I am working on a single page web application and have run into a question for which I cannot seem to find the answer.
Is there a way to load partial views from server side when using angular? I am using nodeJs, with express and Jade, and wanted to load partial views into angular, but I am confused on how I would do such. Is there any particular guideline that I should follow to structure my files?
I do not want to load all of my partials from angular, so I wanted to know if there is a way to load the views in from node.
EDIT: What I mean to ask is, am I allowed to load in partial jade views on angular? Does that have any effect on the way the page renders?
You can't. Angular is a Single Page Application framework, it means that you application (ie HTML+CSS+JS) is loaded once at first load in the browser, and all what happens is a communication of raw data (JSON over REST for example), Angular is in charge of displaying correctly the already-loaded-html correctly according to these raw data.

Express & Backbone Integration

Ok, I am new to web dev and here's a stupid question. I have been through a few tutorials for node, express and backbone individually, but I can't seem to wrap my head around how they are integrated. Particularly, consider this use case:
Person X opens the browser, types in a URL and hits enter->Express responds to the request and sends some data back to the browser.
My question is, where does backbone come into the picture here ? I know it's a mvc framework to organize your JS code. But, I can't find a place in this use-case where the server/browser interacts with backbone. Only thing I can think of is that the backbone saving the route and serving the page the next time. But what about the first time ? It would be best if someone could explain to me how the request gets routed from client browser to express/backbone to browser again.
Also, am I correct in assuming response.send() or response.json() will send the result to backbone when model.fetch() is called ? I mean, is there no additional code required ? Being new to web dev, I'm quite not used to the idea of the framework 'taking care' of everything once you send the response back.
EDIT : Here's what I have understood so far. Feel free to correct me if I am wrong. When I access websites like gmail, the server first sends a big html file including backbone.js code in it. The backbone.js code listens for events like clicking on links in the html file and handles them if the links are defined in it routes(routes are always relative to current route, accessing a completely different route sends request to the server). So, if I click compose, my url remains the same because backbone handles the request. However, if I click Maps/News services in the bar above, the server handles the request.
There is no special integration between backbone and node.js.
If you use the standard backbone sync method then all you need to do is:
Use the static middleware in express to serve up your static html/js/... files.
Define RESTfule routes in express that conform to what backbone is expecting.
Backbone does indeed make an http call when you do model.fetch. You could look in Chome network tab to see where it's sending the request to and then implement that route in express.

Best way to handle Javascript rendering vs. Server side template [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reusing backbone views/routes on the server when using Backbone.js pushstate for seo/bookmarking
I am using Backbone.js and bunch of other modules to handle Single Page App method. My goals:
The site must be SEO-friendly
Server bootstrap html code to client and data stored in JSON models.
Sub-sequence actions are all handled by Javascript (e.g. render new screen, change url using Backbone router).
My question is: how to structure the server to align with Javascript on each router url and keep it DRY?
For example: if user goes to wwww.mysite.com and then click on some link to go to www.mysite.com/page/2, it must be the same as having him to go to www.mysite.com/page/2 directly on first load.
This seems to be an old topic but I cannot find any solid resource about best way to handle this on server side without repeating the template code in Javascript.
One option I am thinking is to split backend into Node.js and another server to handle API only. The Node.js server somehow share the template construction code as the Javascript frontend
Anyways, love to hear some advice and apology if this is not the right place to ask such question.
I would treat my node server as just a REST interface to my data. I would then handle everything else client-side: I could load templates using require.js with a template plugin like jade, do all my routing using Backbone.Router, and then access my models and collections using Backbone.sync methods (like collection.fetch().)
So for example, when a user accesses "mysite.com/#page/2", I could get my Backbone router to load and display whatever template would be on the page. If I happened to need a list of products to display on that page, then I could make my product collection do a product.fetch(). That would send a GET request to "/products" -- or whatever URL is specified in product.url. My node server would then respond with an array of product objects that the view my collection belongs to could use in rendering itself.

How to build a website on Node.js?

I've just started diving into Node.js after several years of PHP programming and I would like to build a Node.js app for my next project, but I have no clue how to do it.
Are there any resources for a Node.js jumpstart?
Thanks in advance!
You should think of Node.js as some kind of Apache + PHP, meaning that you can program your website and your webserver with Node.
Node has some important differences with your basic PHP, it's evented, asynchronous, non-blocking. You have to learn how to deal with callbacks, don't block the event loop and other things.
What you should do is try to learn the basic stuff with Node at the beginning, here are some great resources: https://stackoverflow.com/tags/node.js/info (my favorite has been nodetuts.com and the excellent book by it's author, Hands on Node).
After you've learned the basics, you can find Express really useful as a web framework and Socket.IO if your app is focused on real-time.
I think you're searching for a node.js jump start to build some meaningful web page with node. Take a look at express, which is a node web framework. They offer a nice but short tutorial (under guide).
You need to run Node.js on a web server. Basically, you need a VPS or Dedicated Server over which you have full control. [PHP runs through the standard web server, Apache. Node.js is the webserver.]
Or you find a Node.js host that'll do it for you.
Node.js is essentially your webserver that would replace Apache so the only hosting that you would find to run Nodejs is a dedicated server or a cloud instance in which you would have to install and run nodejs on. The machine that you run node.js on needs to have a domain name pointed to it or the only way you can access the server is by its IP address which is this case your localhost.
Another option is to use something like Knockout.js (http://knockoutjs.com/), and have the page make JSONP calls to the Node.js server. It's really easy to use Node to send JSON to the client, since it's JavaScript on the server. Using a framework on the client makes it really easy to create a dynamic page based on that JSON data.
The disadvantage is there is no graceful degredation for older browsers. The advantage is a potentially blazing fast website with great AJAX built-in right from the start.
Here is some sample code for using Node to generate a JSONP response:
function writeJsonpResponse(res, jsonpcallback, obj) {
var serialized = JSON.stringify(obj);
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.write(jsonpcallback + '(' + serialized + ');');
res.end();
}
Read the README.
Setup environment.
take a look at package.json (or npm init to create one)
install dependencies (npm install / axios, nodemon, express, mysql, react, babel)
add scripts to start server & webpack if needed
Get acquainted with file structure.
separation of concerns - public/dist, server, db, client
think about the flow of data
Ensure basic HTML structure.
check that bundle.js file / everything it needs is loaded in
need a div id to render react with (like app or root)
Spin up Express server.
Start server and webpack is separate terminals.
check for console.log that server is listening!
Write routes (get and post requests) on your server.
check that get & post requests are working w/ Postman!
Create mySQL database (db/index.js).
Design & import schema (how to structure data tables).
make sure you’re in the db folder when importing yr schema girl!
Connect db to server.
check for console.log that connection is successful!
Write insert/retrieve db query functions.
don’t forget to module.exports those queries to the server!
will call query functions in routes/get & post requests in server
Set up basic React structure.
index.js’s only task is to render your app component to the div id app
need a stateful App component to render all other components
remember to import & export default everything!
Design the rest of your components, decide whether or not they will be functional (stateless) or class components (stateful).
draw it out!
what props (data & functions) do you need to pass down?
Write those components.
Work through one data flow that executes through all the pieces. Get your input handler to send the client side POST request (using axios) to the server route, which will execute your API call (if there is one) and then insert that data to the database.
remember to handle your errors!
Handle events / conditional rendering.
1. user event gives input (onChange e.target.value)
2. write a handleChange f(x) to update state to that new input
3. input is submitted (onClick)
3. write a handleSubmit f(x) that takes in the updated state and makes an axios POST request w/ that { input } to the appropriate server route
remember to bind method functions appropriately!
Call query functions in routes/get & post requests.
Check that data from the client is being stored in the database.
describe those tables my friend!
Do an AJAX get request (use axios or fetch) on client side to api endpoint.
Store the incoming data in setState
May want to do a GET request in componentDidMount to always render appropriate info for client
Yay! You successfully set up your server, database, and client, passed data between them, potentially manipulated the data, stored that data, and displayed the appropriate data to the client!
Tackle those user stories!

Resources