为什么AngularJS将X-XSRF-TOKEN标头作为JSON字符串发送?

前端之家收集整理的这篇文章主要介绍了为什么AngularJS将X-XSRF-TOKEN标头作为JSON字符串发送?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Angular sets the X-XSRF-TOKEN header to the value of the XSRF-TOKEN cookie:

var xsrfValue = isSameDomain(config.url,$browser.url())
                ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
                : undefined;
if (xsrfValue) {
  headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}

但是,如果使用$cookieStore设置XSRF-TOKEN cookie(例如,对于Rails集成):

$cookieStore.put("XSRF-TOKEN","my_token");

the cookie is stored as JSON string:

put: function(key,value) {
  $cookies[key] = angular.toJson(value);
}

这意味着标题将具有额外的双引号:

X-XSRF-TOKEN    "my_token"

为什么Angular在设置标头的值时不调用fromJson(),以使标头看起来像这样:

X-XSRF-TOKEN    my_token

这样可以避免我们删除服务器端的额外双引号.

我错过了一些明显的东西吗?

注意:我不是在寻找解决方法.我试图了解这种行为是否是预期的行为,如果是的话,理由是什么?

解决方法

Here is the official answer I got:

The real problem here is that you are trying to use the $cookieStore
for the wrong purpose. The $cookieStore is an abstraction on top of
$cookie,which works with objects and serializes them to JSON. If you
want to assign the XSRF token then just use $cookie to write it,which
works directly with strings.

换句话说,应该做的事情:

$cookies [“XSRF-TOKEN”] =“my_token”; //存储为:my_token

而不是:

$cookieStore.put(“XSRF-TOKEN”,“my_token”); //存储为:“my_token”

猜你在找的Angularjs相关文章