简体   繁体   English

在Rails 4和Ember中的所有子域上设置Cookie

[英]Setting a cookie on all subdomains in Rails 4 and Ember

We have a Rails application that is the API component running on api.domain.com and a front-end application in Ember.js running on www.domain.com . 我们有一个Rails应用程序,它是在api.domain.com运行的API组件,而在api.domain.com一个在www.domain.com运行的前端应用程序。

When Ember.js sends a POST request to a route in the API, /events , we want the API to set a cookie to remember a unique user identifier. 当Ember.js将POST请求发送到API中的路由/events ,我们希望API设置cookie来记住唯一的用户标识符。

Hence this method in the Events controller: 因此,事件控制器中的此方法:

def set_tracking_cookie
  cookies[:our_company_distinct] = {
    value: create_identifier,
    expires: 1.year.from_now,
    domain: :all
  }
end

As you see, the cookie is set on the entire domain, and is set to expire in a year. 如您所见,cookie设置在整个域上,并设置为在一年后过期。

The point is that the next time Ember queries the API, it will be able to read this cookie. 关键是,下次Ember查询API时,它将能够读取此cookie。 However, this is not the case. 然而,这种情况并非如此。

Each time the front-end queries the API, the API is unable to find the cookie, nor does it show in the cookies in my developer tools. 每次前端查询API时,API都找不到cookie,也不会在我的开发人员工具的cookie中显示它。

The Ember requests set the Access-Control-Allow-Credentials header to true , and I can confirm that the cookie is indeed sent in the response from the API with the correct values for domain, name, path, expiry, etc. Ember请求将Access-Control-Allow-Credentials标头设置为true ,并且我可以确认Cookie确实是在API响应中使用域,名称,路径,有效期等的正确值发送的。

Am I missing something? 我想念什么吗?

Thanks! 谢谢!

For anyone else going through a problem sending/receiving cookies in this way, here are some things I found helpful when I was debugging and ultimately fixed the problem: 对于通过这种方式发送/接收Cookie遇到问题的其他任何人,在调试并最终解决该问题时,我发现有些有用的东西:

  • When you use the Chrome's (or any other browser's) devtools, examine each request and check it to see if the cookie is being sent from the API on the request where you expect it to be sent, and if all subsequent requests from Ember (or whatever other JS framework for that matter) send this request. 当您使用Chrome浏览器(或其他任何浏览器)的devtools时,请检查每个请求并进行检查,以查看Cookie是否已从您希望将其发送到的请求上的API发送,以及是否来自Ember的所有后续请求(或不论其他哪种JS框架都可以发送此请求。 In Chrome, go to "Network > [request] > Cookies". 在Chrome中,转到“网络> [请求]> Cookies”。 Ensure that the front end is sending the cookie properly and that it indeed receives it properly. 确保前端正确发送了cookie,并且确实确实正确接收了cookie。
  • We found that this was the best way of adding support for the CORS cookies to Ember was to be done like so: http://discuss.emberjs.com/t/ember-data-and-cors/3690 我们发现这是向Ember添加对CORS cookie的支持的最好方法,例如: http : //discuss.emberjs.com/t/ember-data-and-cors/3690

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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