Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Backbone.js with express.js - sync using only POST and GET

Backbone.js with express.js - sync using only POST and GET


My app is Backbone.js for client-side, Express.js for back-end.

I have problems with syncing with all parts of my API, using the backbone Model and collection(they use urlRoot: "/users"). I'm allowed to use only GET or POST, no PUT or DELETE. *I'm not allowed to use more models* Not allowed to use jQuery ajax


add new user: I need to make a POST to /users with JSON of new data. So I did it just fine with -{new data...})

list all users: My API for that, responses to GET /users, with the right handler - so, this.collection.fetch() - works fine.

Log-In: My API accepts POST to /users/login for that. How can I add a Function "logIn" to my model, that will use custom sync/pass options.url to sync - or any other way - that will POST to /users/login ?

Log-Out: API accepts POST to /users/logout - how to send this request using my Backbone Model ?

User By ID: Same question here for GET /users/:id

Update user: POST /users/:id - same question again.

--- So actually, the question in short is ---

What is the best way (or the most "right"), to implement methods of a backbone model, that are similar to "" - but just POST/GET to a bit different path then urlRoot ?

Problem courtesy of: Daniel


You probably have a couple options here. One would be structuring your models in a way that supports the urls you want. For instance, have a User model and a Session model that deal with updating the user and managing the logged in state separately.

The other thing you should probably do is to use the url method in your models.

Something like this in your User model. (Note: using urlRoot instead of url here is identical, but this is the correct approach for anything more complicated that is needed in the url)

url : function() {
  var base = "/users/";
  if(this.isNew()) {
    return base;
  } else {
    return base + this.get("id");

You could extend this same concept to work in your Session model for handling logout vs login based on if the Session is new or not.


If you must use the same model, the best thing would be to totally bypass the Backbone.sync method and write a custom AJAX call with success/error handlers that know how to clean things up.

login : function() {
  $.post("/users/login", {success: function (response) {
      // Update user as needed
    }, error: function (xhr, response) {
      // Handle errors
Solution courtesy of: Andrew Hubbs


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Backbone.js with express.js - sync using only POST and GET


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription