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
- traditional way: render html page server
- not sure: create api , let user's browser download javascript application (angular, react, ember) highly interactive application
- 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
Post a Comment