简体   繁体   中英

acquiring session information from server-side code, to client-side code

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM