Javascript/Rails授权获取头部。

4

我正在开发React/Redux SPA应用程序,希望进行授权。我有使用devise_token_auth gem的Rails后端,并且(在React应用程序中)需要保存由后端响应给我的令牌。然而,response.headers 中没有可用的令牌。为什么?CORS已正确设置在后端,所以我确定这不是问题所在。请查看代码和截图:

let config = {
  method: 'POST',
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify(creds) // { email: 'asd@example.org', password: 'asdasdasd' }
}

return dispatch => {
  dispatch(requestLogin(creds))
  return fetch('http://localhost:3000/auth/sign_in', config)
    .then((response => {
      response.headers.forEach((el) => console.log(el))
    }))
}

console.log:

console.log from code above

证明浏览器看到了头部信息:

enter image description here


我建议在sign_in响应正文中仅返回token,而不是尝试将其添加到头部。从安全角度来看没有任何优势。 - Blair Anderson
@BlairAnderson 我使用devise-token-auth,但我找不到相应的配置选项(我不想进行monkeypatch)。不过,JS中看不到所有的头信息确实很奇怪,为了好起见,我会先解决这个问题。谢谢你的回复 :) - Bartosz Gladecki
1个回答

1

问题已经解决,原因在后端。我在我的rack-cors初始化器中有以下内容:

headers: :any,                                                                                                         
methods: [:get, :post, :put, :patch, :delete, :options, :head]

转换成中文:

改为这个:

headers: :any,
expose: ['access-token', 'expiry', 'token-type', 'uid', 'client'],
methods: [:get, :post, :put, :patch, :delete, :options, :head]                                                                                               

现在一切都正常了 :) 在查看devise_token_auth的源代码时得到了答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接