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.
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.
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.
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).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With