【问题标题】:Cookies' update from response delayed in future来自响应的 Cookie 更新将在未来延迟
【发布时间】:2014-01-23 23:33:05
【问题描述】:

我在ngCookies 服务中遇到了一个奇怪的问题。主要是在收到来自我的/api/auth/login/ 端点的响应后,带有标头:

Set-Cookie  csrftoken=gxCld8gEga71MuQPQbjDujDBvR4HwPvu; expires=Sun, 28-Dec-2014 15:31:38 GMT; Max-Age=31449600; Path=/

$cookies['csrftoken'] 在未指定的时间后更新。这个事实已经记录在docs:

Only a simple Object is exposed and by adding or removing properties to/from this object, new cookies are created/deleted at the end of current $eval.

知道了这一点,我求助于使用$timeout 来希望将我的代码评估延迟到上述$eval。

最终得到以下(CoffeeScript):

login = () ->
    deferred = $q.defer()

    $http.post('/api/accounts/login/', data)
    .success((data) ->
        args = arguments
        $timeout(() ->
            do_fancy_stuff()
            deferred.resolve.apply(deferred, args)
        )
        return
    ).error(() ->
        args = arguments
        $timeout(() ->
            deferred.reject.apply(deferred, args)
        )
        return
    )

    promise = deferred.promise
    promise.success = promise.then
    promise.error = promise.catch
    promise

但是上面的代码仍然存在这个问题。在$timeout 启动后,Cookie 会使用来自响应方式的值进行更新。

在添加console.log('cookies push', $browser.cookies().csrftoken, cookies.csrftoken); here 之后(在if 语句之后)。我最终得到了这样的结果:

如您所见,打印 7 次后令牌相等。

yhQqT6KOfSKYCNB3Ag4sEPllMgkLrVj1 令牌来自上一个会话。我正在测试注销并进入应用程序而不刷新页面。 Setting X-CSRFToken 直接在我的do_fancy_stuff() 函数中调用(没有异步的东西,只是裸$cookies['csrftoken'] 访问)。

还需要使用$q 来提供类似$http 的承诺作为返回值(如果cookie 工作正常,则不会有$q)。

【问题讨论】:

  • 我想我遇到了类似的问题。解决方案有进展吗?
  • @SethM.,我实际上已经做到了,以便我的 login 视图返回带有令牌值的 X-CSRFToken 标头。这样,就可以在即将到来的请求的响应中直接设置默认的$http 标头。请注意,我声称这是一种 hack 而不是解决方案。

标签: angularjs coffeescript angular-cookies


【解决方案1】:

$cookies 服务有一个 pollerfn 复制来自 $browser 的所有 cookie,并且此轮询器每 100 毫秒定期执行一次。因此最好将 $timeout 放置 150 毫秒以避免边缘情况。

【讨论】:

    【解决方案2】:

    我根据here 和here 找到的信息选择使用的解决方案。告诉我 $cookies 将尝试每 100 毫秒刷新一次。因此,考虑到这些信息,您可以为任何需要使用响应 cookie 的请求添加 $timeout。

            $http.post(url, tokens)
                .success(function(result, status, headers, config) { // sign in successful
                    $timeout(function() { /* do stuff with $cookies here. */ }, 100);
                })
                .error(function(data, status, headers, config) {
                });
    

    【讨论】:

      猜你喜欢
      • 2013-01-02
      • 2019-08-05
      • 2018-10-13
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多