Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am working on re-writing an existing web site using Node.js with Express.

Front-end of the site will use Backbone JS and thus I need to have all necessary routes comply with native Backbone sync. Now most of URL's the client and for Backbone sync will be same. But they won't work for regular GET as they would need to return JSON.

So I am thinking, would it be a good idea to add extension to Model/Collection URLs in Backbone, such as .json, and in Express to have this for every route:

app.get('/p/:topCategory/:category/:product.:format', function(req, res) { ... });

Where if (req.params.id == 'json') than we send JSON, otherwise we render HTML?

Or is there a better approach? Please help.

like image 693
mvbl fst Avatar asked Jun 09 '12 03:06

mvbl fst


People also ask

What is route route in express?

Route methods. A route method is derived from one of the HTTP methods, and is attached to an instance of the express class. The following code is an example of routes that are defined for the GET and the POST methods to the root of the app. Express supports methods that correspond to all HTTP request methods: get, post, and so on.

What are route paths in JavaScript?

Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.

What is a REST API?

An API is always needed to create mobile applications, single page applications, use AJAX calls and provide data to clients. An popular architectural style of how to structure and name these APIs and the endpoints is called REST (Representational Transfer State).

What are routing methods in Laravel?

These routing methods specify a callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method.


2 Answers

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

like image 91
alessioalex Avatar answered Sep 20 '22 00:09

alessioalex


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

like image 42
ebohlman Avatar answered Sep 19 '22 00:09

ebohlman