How to architect a single page, API-consuming app using NodeJS - javascript

I need to build a single-page JavaScript web app that, on regular intervals, pulls data from a couple of public and maybe a few private APIs, and present & refresh the data in different tables. I could build it purely as front-end code with jQuery and just use AJAX calls, but to keep the keys and everything for the APIs private, I need the logic that retrieves the API data to live in backend code (on the same server).
I'm new to building this kind of application, and wondering how to achieve this with NodeJS. After searching and looking at some tutorials, the only way I can wrap my head around it so far is to have an index.html that displays the view with the empty tables, then on a setInterval, have a local JavaScript function do an AJAX call to a NodeJS (Express) route that handles all the API stuff and returns a JSON object in the response. On success, the local JavaScript can write the results to the html for the various tables/divs.
That sounds OK to me, but since all of this will have to live on the same server, it seems really weird to have a front-end script do manual calls to that same server via a URL/route.
What am I conceptually missing? Do I need to employ a master Express layout and use partials for the divs/tables and have the Node backend process the front-end that way? Or should I stick to building .html and .js outside of Express and maybe use something like Angular to create a more intuitive front-end piece? I'm not sure how either of these scenarios would be put together, I'm just feeling around for a better approach.

Posting as Community Wiki answer, as this got answered in comments:
The way I would approach this is with an Angular app. Exactly as you state you would have an API that is built on nodeJS (a bunch of defined routes that grab data and return JSON), and then your front-end angular app. Correct, every set interval your app would call the endpoints you defined in your API, and then update $scope variables based on the JSON response. Your HTML would actually be updated in real time automatically (since that's how angular works with binding models and templates/partials). I would look into angular - sounds like a perfect solution!
Also, once you understand how the binding of angular works, you will never want to write jQuery html() append() or any of those DOM manipulation functions again.

Related

What role does an API serve in MVC?

I'm still trying to understand MVC to it's fullest.
I know that in a normal setup, the user requests a webpage. That request gets read by the controller and if for example the user needs to see 5 blogposts, it asks the Model to retrieve 5 blogposts out of the database and give those back to the controller. The controller then sends those 5 blogposts to the View, where they get inserted into a normal webpage. The View then returns the data to the user and they see 5 blogposts on the website. (Please correct me if I am wrong. I find it really hard to grasp, for some reason.)
Now I am using React in a project and I would like to do API calls to my PHP to retrieve data.
Does this mean that if I request "website.com/api/blogposts/5", the Controller in PHP reads that it's an api call, asks the Model for 5 blogposts and sends this data back as a response. This would make React the View, right?
Sorry if this is supposed to be basic information. I just can't wrap my head around it.
It seems like you might be conflating a few concepts so let's take a second to separate them.
Let's talk about web API's first, based on the context you've given you're trying to build a react app that communicates with a PHP API. MVC doesn't necessarily apply here. It exists as a separate application so trying to think of them together in some kind of MVC architecture is going to cause confusion. This API could feature an architecture like REST and would be built to serve data to your client-sided application.
React, my knowledge of the platform isn't extensive however in theory you could map out some type of MVC style architecture in how you structure your project, but React isn't an MVC framework. It's very component based and designed to create reusable components for single page applications. You can read more about this here.
MVC, I find it easiest to explain using asp.net mvc as an example but I'll try to explain a way that doesn't depend on that. MVC is a principle seen most in the typical server-sided web page loading platform. The view being the web page, the controller being a route on a server, and the model defining the data seen on the page which was returned by the server. Most of your MVC guides will explain this pretty thoroughly.
To summarize, if you're trying to learn React for your front-end applications and design an API in PHP to use with it, you'll want to learn React how it was designed to be used. For the API, take a look at good REST practices and just general PHP API designs. If you want to learn MVC, checkout an MVC framework that is built on top of that principle. The concept has some age to it now, so some of the newer technologies like React don't really use the same principles.
Does this mean that if I request "website.com/api/blogposts/5", the Controller in PHP reads that it's an api call, asks the Model for 5 blogposts and sends this data back as a response. This would make React the View, right?
This could be an approach. However, since i've done this before I strongly recomend not to put the API logic inside the controllers. If your application tends to scale, your controller will become huge, and that is something you want to avoid.
What you should probably do is to create a restful implementation that handles the requests and validations, and from there you can call your controllers to retrieve the processed data and then answer the request. With this approach you will get more maintanable and consistent code.
And of course, you will keep your MVC pattern implementation clean and pure.

How to build a REST client frontend for a REST API backend?

I've built a REST API backend using Django and am now at the stage of designing a client facing frontend. Though, I can't seem to understand how this client frontend should be structured and which languages it should use.
PHP is server-side, and is usually used as the language for building backends. When coupled with a framework such as Codeigniter, it can also be used to play around with sessions, route URLs, and decide which templates to use. Though, I don't believe it can be used to call my REST API to fetch resources (might be wrong here, correct me please if I am).
Javascript is client facing but is used only once the webpage has been fetched from the server. AngularJS is great, but from what I've read, it seems it only helps add very dynamic functionality into already rendered static pages.
I am really open to any ideas, suggestions, and advice based on your experiences creating client frontends. So, back to my original question, how does one structure a REST client frontend, which language is best for this goal, and if which frameworks should one consider to use?
Update 1
Someone asked whether this client frontend will be run in a browser -- the answer is yes, it will. I am trying to build a Twitter-like web client frontend that interacts with a Twitter-like REST API backend. Basically, everything you see there when you go on Twitter's website.
Since it is a browser frontend I would go with HTML/JavaScript only. No need to use PHP or any server side language IMHO. This has the advantage of being extremely portable.
I would also use a JS framework for that purpose ( the trend nowadays seems to be angular).
REST really, really isn't new. It's been a part of HTTP at least as far back as HTTP 1.1
Have a look at this question: Backbone.js frontend with RESTful Rails backend? the top answer lists 20 possible frameworks for building a front end.
Thanks for your help, everyone. Found exactly what I was looking for here:
http://docs.python-requests.org/en/latest/
A nice little library for Python that allows me to basically make calls to a REST backend from within a Django application, which serves as my frontend.
AngularJS will also be used for to make the static pages that Django returns more dynamic. Why? Because AngularJS by itself can be the complete solution only if your whole site consists of one page. If you have multiple pages where each one has it's own set of dynamic elements, you need a combination of Django and AngularJS.
Apparently REST is still quite new and it seems there aren't many people that have stumbled upon this very fundamental question like I have.
Once again, thanks!

Rendering templates using backbone and Express

I'm currently working on web development side project. I have been trying to figure out all the pieces for the last couple of months and have made good progress.
I'm using bootstrap and Backbone on the front end and this is what I have been focusing on lately. This part works well with all the Backbone views being rendered fine.
For the backend I will use Nodejs along with express. I have started looking into it this past week. Currently, I'm trying to serve requests sent to the server with through express.
How can I handle the request and send back a Backbone view that already has a defined HTML page and everything.
I came across Jade which is used with express a lot but I can't get it to work with my backbone views. Also, how does underscore come into the picture. Do I have to choose between underscore and Jade?
I will of course further down the line have data pulled from a database and sent to the backbone views.
Thank you for any input.
Underscore (_.template method) and Jade both can, from a template file, render html code which will be sent by express to the client. Since underscore is not express friendly my guess is that you are confusing the client libraries (Used by backbone on the browser) and the server libraries user by nodeJS to answer request calls, if you are rendering templates using underscore with backbone that is done client side and has nothing to do with express.
This article should help you set everything up: http://coenraets.org/blog/2012/10/nodecellar-sample-application-with-backbone-js-twitter-bootstrap-node-js-express-and-mongodb/ and it has source code for you to look at.
Since my guess is you want something functional fast, I would suggest something like sails.js which can save you a lot of time configuring express and making it work. Plus sails.js its built on top of express. https://github.com/balderdashy/sails/

Do I have to use a Backend when using Backbone.js?

I want to develop a relatively simple application that calculates some value based on several inputs. I dont want a backend, all the calculation can be done in the browser.
Im a little new to JavaScript and WebApps and I came across Backbone.js.
I really like the MVC design, however, they mention a backend a lot. My question:
Is a backend server absolutely required?
Is a backend server optional but without one there isn't much point in backbone.
Or will backbone will really help me out?
Backend is not required.
Backbone can fully work without any backend if your application doesn't require one.
That depends on your application. If you want to retrieve value of some inputs and calculate a result then Backbone won't do that for you - it will help you structure your code. If you app is simple and don't need support for models, views and collections or routing, then there is no point in using Backbone. Hard to answer this question.
For example: Classic todo example application doesn't use any backend.
Backbone.js implements fetch(), save(), destroy() etc. methods on models automatically performing appropriate AJAX requests and parsing response. So it has a strong support for backend via REST services, but it is optional.
You can still use models, views, routers and events without any server-side code. Just don't call REST methods (or override them at your wish).
You can use localStorage for persistence (you'd have to implement this yourself or find it on the web, like here) but if you don't even need that then you don't need to use any of the persistence methods in backbone.
Backbone is meant to help you structure a medium-large sized application (js-wise), so it doesn't become unmaintainable jQuery spaghetti. With short applications (js-wise) it's really an overkill unless you are trying to learn how backbone works.
Note with js-wise I mean the client side code, if you had a huge backend but the only js would be something that focuses some form, it would not even count as a short application (js-wise).
You can use backbone.js without a backend. However you obviously won't be able to store or retrieve data. Backbone may still be useful for keeping your code organized, however it really shines when you want to separate presentation logic from logic that manipulates your data, which is a goal of the MVC pattern. Generally your data will be stored on and retrieved from a backend.
If you want to play around with data persistence, try out backlift.com. [disclosure, I work on backlift.com] We've tried to make it easy to get a backbone app up-and-running without having to setup a server or deal with compiling templates.

Javascript AJAX API generation for Django

I have a Django page that uses AJAX in some places to enhance the page. Currently the backend for these AJAX calls are normal Django views that return JSON and the URLs to these views are hardcoded in Django.
I'm currently looking for different, nicer way to solve this. My idea is the following: Have some "magic" that takes Python code within Django and exposes a API for it. Additionally, a JS file is generated that can be included into the page that exposes this API to Javascript. Ideally all underlying work is hidden. Is there a project that does this? Or are there alternative ways to do this?
There are many modules designed for API-building, but I don't think any of those (Django REST Framework, Piston, Tastypie) fits your needs.
What maybe is something that is similar to your description is the Dajax Project - it has some automatic ajax registration stuff.

Categories

Resources