在 XHR 响应中发送 cookie 但它没有被存储?

Sending cookie in XHR response but it's not getting stored?

我正在尝试传递一个 HttpOnly cookie,其中包含我正在写的 API 的响应。目的是让 cookie 像刷新令牌一样用于 React 中的 SPA silent refresh

在我的控制器方法中,我得到了以下代码:

response.set_cookie(
  :foo,
  {
    value: 'testing',
    expires: 7.days.from_now,
    path: '/api/v1/auth',
    secure: true,
    httponly: true
  }
)

我正在使用 fetch 命令对此操作发出 post 请求,如下所示:

fetch("http://localhost:3001/api/v1/auth", {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    email: 'aaron@example.com',
    password: '123456',
  })
})

不确定这是否重要,但我想知道在 XHR 响应中传递 cookie 是否不起作用?但是,正如您在我的回复中看到的那样,这似乎有效,我得到了这个:

Set-Cookie: foo=testing; path=/api/v1/auth; expires=Sun, 26 Jan 2020 05:15:30 GMT; secure; HttpOnly

也在 Cookies 下的 Network 选项卡中,我得到了这个:

但是,我没有在 Application -> Cookies 下设置 cookie:

澄清一下,React 应用程序位于 localhost:3000,rails 后端正在侦听 localhost:3001

有什么想法吗?

好的,看来我需要配置我的 CORS(在 Rails 中这是你的 Rack::CORS 中间件。

我这样设置 config/initializers/cors.rb 文件:

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3000'
    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head],
      credentials: true
  end
end

我的获取命令应该看起来像这样,使用 credentials: 'include' 作为参数:

return fetch(`${endPoint}`, {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      email,
      password,
      password_confirmation: passwordConfirmation
    })
  })

添加 credentials: true 允许浏览器设置 cookie。显然,即使您发送它们,您也需要 headers 中的 Access-Control-Allow-Credentials: true 以便浏览器对它们执行任何操作。

编辑: 重新创建此应用程序以获取学习经验 即使在包含 credentials 选项后,我还是再次遇到了这个问题。我没有看到 HttpOnly cookie 存储在浏览器中。然而事实证明,它确实被发送了。您可以在控制器操作中对此进行测试。如果此解决方案不适合您,请记住这一点!'seem'!