刷新页面时Meteor.userId不会保留

时间:2013-07-17 14:11:11

标签: javascript node.js meteor

我正在使用Meteor 0.6.3.1并且已经创建了我自己的用户系统(不是真正的用户系统,但我想我也可以使用userId变量,因为没有其他人声称它。)

问题是,变量不是持久的。

我有这段代码

Meteor.methods({
    'initCart': function () {
        console.log(this.userId);

        if(!this.userId) {
            var id = Carts.insert({products: []});

            this.setUserId(id); 
            console.log("cart id " + id + " assigned");
        }

        return this.userId;
    }
});

关键是,您应该可以切换页面但仍然使用相同的购物车。

我不能使用Sessions,因为它们是客户端的,可能会导致用户之间的信息泄露..

我应该怎么做呢?有没有像服务器端Meteor的Amplify那样的东西?

2 个答案:

答案 0 :(得分:2)

来自Meteor docs:

  

setUserId不具有追溯力。它会影响当前的方法调用和   任何未来的方法都会调用连接。任何先前的方法调用   在此连接上仍会看到其中的userId的值   他们开始时的效果。

刷新后,您可以创建新连接。在该连接上,您使用客户端用户系统存储的cookie登录。

您可以将购物车ID存储在Cookie中......

答案 1 :(得分:-1)

这对我有用:

# server/methods/app.coffee 
#---------------------------------------------------
# Info found in Meteor documentation (24 Feb. 2015)
#
#   > Currently when a client reconnects to the server 
#   (such as after temporarily losing its Internet connection),
#   it will get a new connection each time. The onConnection callbacks will be called again,
#   and the new connection will have a new connection id.
#   > In the future, when client reconnection is fully implemented, 
#   reconnecting from the client will reconnect to the same connection on the server:
#   the onConnection callback won't be called for that connection again,
#   and the connection will still have the same connection id.
#
# In order to avoid removing data from persistent collections (ex. cartitems) associated with client sessionId (conn.id), at the moment we'll implement the next logic:
# 
# 1. Add the client IP (conn.clientAddress) to the cartitems document (also keep the conn.id)
# 2. When a new connection is created, we find the cartitems associated with this conn.clientAddress and we'll update (multi: true) the conn.id on the all cartitems.
# 3. Only remove the cartitems associated with the conn.id after 10 seconds (if in this time the customer reconnect, the conn.id will have been updated at the point #2. we avoid this way removing after refresh the page for example.
# 4. After 10 seconds (ex. the user close the window) we'll remove the cartitems associated with the conn.id that it has been closed.

Meteor.onConnection (conn) ->
  CartItems.update({clientAddress: conn.clientAddress}, {$set: {sessionId: conn.id}}, {multi: true})
  conn.onClose ->
    Meteor.setTimeout ->
      CartItems.remove {sessionId: conn.id}
    , 10000

Meteor.methods
  getSessionData: ->
    conn = this.connection
    {sessionId: conn.id, clientAddress: conn.clientAddress}