Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should views be rendered by the app, or should a static site contact the API using AJAX?

I am starting to write my first web app with Node.js and Express. I have two approaches in mind.

  • Create two sets of routes. One that sends JSON, one that renders the page using a templating engine
  • Create a static website that makes API calls to the backend using AJAX, and have only routes for the API.

I understand that approach #2 depends on AJAX support in the browser, but if this was your project, based on the advantages and disadvantages of each approach, which would you choose and why?

like image 226
728883902 Avatar asked Jan 19 '18 13:01

728883902


1 Answers

If I am reading it right, both options #1 and #2 first set of routes is an API that returns JSON rather than sends it.

Assuming that in #2 you wouldn't create static pages with JavaScript doing AJAX calls, but rather still use express static routing like app.use('/', express.static(path.join(__dirname, 'dist'))); the difference between 2 approaches isn't that big.

Unless you already know some supported template language, such as mustache the cons are that you have to learn one and before that pick one (which isn't always an easy task from my experience!).

If you don't know one, depending on your application, you might still benefit from learning and using one. As an example you can think of a very generic UI where a single template could be reused very many times - like a generic database UI similar to, say well known phpmyadmin.

In case of static routing, you can achieve similar results by using a JavaScript framework which has components or templates, such as angular. If you aren't planning to use one, that could result in a lot of code duplication of otherwise re-usable widgets. And even when using one I can imagine a case when template engine would result in less code (or less files in your project at the very least). Not sure though if it's going to be easier to navigate and moreover to cover with tests when the project grows.

Without knowing more about your project it is hard to give more advice.

like image 87
isp-zax Avatar answered Jan 03 '23 14:01

isp-zax