Set up REST routes in Express JS for Ajax only to use with Backbone Set up REST routes in Express JS for Ajax only to use with Backbone express express

Set up REST routes in Express JS for Ajax only to use with Backbone


The better way of doing this would be to use the content negotiation feature in Express 3.x, namely res.format:

https://github.com/visionmedia/express/blob/master/lib/response.js#L299-378

res.format({  text: function(){    res.send('hey');  },  html: function(){    res.send('<p>hey</p>');  },  json: function(){    res.send({ message: 'hey' });  }});

You approach is also ok, Yammer for ex. is using the same approach: http://developer.yammer.com/api/#message-viewing


Use Accept headers in your requests: Accept: application/json if you want to receive JSON, Accept: text/HTML if you want HTML.


An alternative that also checks that the "X-Requested-With" header is set for jQuery et al.

var onlyAllowJsonRequests = function (req, res, next) {    var acceptJson = (req.accepted.length && _.any(req.accepted, function (acc) { return acc.value.indexOf("json") !== -1 }));    // also check that "X-Requested-With": "XMLHttpRequest" header is set    if (acceptJson && (req.xhr === true)) {        next();    } else {        res.send(406, "Not Acceptable");    }};app.use(onlyAllowJsonRequests);

NB underscore is a depency.