Reputation: 5026
On a website I'm developing, using Node, Express, and Backbone, I have the user login using a regular HTML form that, when successfully logged in, creates a user session. Accessing this session info is easy on the server-side, giving me access to the User ID, Username, etc., but I'm not sure on how to access this information in Backbone.
I want to acquire the UserID such that I can create a URL for a Collection like this:
url: '/api/users/'+ this.userID +'/movies';
But I'm not sure how to best go about acquiring the userID based upon the Session data that's on the server-side. Would this require creating another model -- say, a 'User' model that fetches the session data from the server, through a particular url/get request?
Thanks!
Upvotes: 1
Views: 624
Reputation: 5026
I came up with something, but would still be open to suggestions:
First, create a function in Express.js that returns the userId:
app.get('/api/current-user', middleware.requiresLogin, function(req, res){
res.send(req.session.user._id);
});
Second, on the client side, retrieve the ID using either a Backbone model or $.get request:
var userID = $.get("/api/current-user");
$.when(userID).then(function(data){
var user = new userCollection(data);
user.fetch();
});
With your collection and model doing this:
window.userModel = Backbone.Model.extend({
idAttribute: "_id"
});
var userCollection = Backbone.Collection.extend({
model: userModel,
initialize: function(options){
this.url = "/api/users/"+options+"/movies";
this.model.urlRoot = "/api/users/"+options+"/movies";
}
});
myModel.save(); then works correctly.
Upvotes: 3