发出API请求时未将Cookie发送回服务器

时间:2020-05-10 05:17:47

标签: ruby-on-rails api cookies

我正在用React前端在Rails中开发一个API。我正在连接身份验证,但忘记了一些东西。对/ api / v1 / me的第一个请求应该得到401,然后我进行身份验证并得到了cookie,但是当我对/ api / v1 / me的第二个请求时,没有发送该cookie。我过去做过这项工作,但似乎忘记了如何做。

enter image description here

我在服务器上使用Rails 6.0.2.2,我确实尝试添加此初始化器文件:

Rails.application.config.session_store :cookie_store, key: 'session', domain: :all

并且我已经(临时)启用了CORS:

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "*"
    resource "*", headers: :any, methods: :any
  end
end

1 个答案:

答案 0 :(得分:0)

我找到了答案。我需要在CORS设置中添加credentials: true,因此,如下所示:

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "localhost:3000"

    # resource "/api/*", headers: %w[Authorization], methods: :any, expose: %w[Authorization], max_age: 600
    # resource "*", headers: :any, methods: :any
    resource "/api/v1/*",
             headers:     %w[Authorization],
             methods:     :any,
             credentials: true,
             expose:      %w[Authorization],
             max_age:     600
  end
end

,我还需要在发出请求时将withCredentials: true传递给axios:

axios.get(`${apiEndPoint()}/me`, {withCredentials: true})