node.js - can I create a route that could be use both for serving HTML and REST API? -


okay here's scenario, knowledge there 3 ways create web application

  1. traditional way: render html page server
  2. not sure: create api , let user's browser download javascript application (angular, react, ember) highly interactive application
  3. the future: isomorphic web app, render html client-side technologies (angular, react, ember) server.

i'm planning use third way, due faster load page, problem right if create mobile application.

my stack: node.js + react

let if i'm planning go mobile, need duplicate same route , logic ? current problem

app.get('/users', function(req, res) {    res.render('index', { message: "hey im jack" }); });  app.get('/api/users', function(req, res) {    res.json({ message: "hey im jack" }) }); 

is there way use 1 route serve both html , rest?

you can send either html or json (in case of rest).

the /api/xxx route syntax makes clearer path serves json.

but can depend on client's request header check whether requested json or html

app.get('/users', function(req, res) {     if (req.headers.accept && req.headers.accept.match(/json/))         res.json(data);     else         res.render('index', data); }); 

angular's $http requests json default, not sure others, can set headers. browsers request text/html, i'm not sure.

or if you're concerned not having repeat logic fetches data, put middleware preceeding both:

// regex match both routes app.get(/.*users/, function(req, res) {    res.locals.data = { message: "hey im jack" };    req.next(); });  app.get('/users', function(req, res) {    res.render('index', res.locals.data); });  app.get('/api/users', function(req, res) {    res.json(res.locals.data) }); 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -