devise token auth - 如何使用javascript访问响应头信息?

har*_*dik 2 javascript authentication ruby-on-rails devise vue.js

我正在开发一个 Web 应用程序,使用 Rails 作为后端 API,使用 vue.js 作为前端库。为此,在身份验证期间,我使用devise_token_auth库。现在看来它正在响应的标头内发送令牌信息,我不知道如何使用 javascript 检索该信息。

\n\n

我还表明他们有单独的库,例如J-toker、\n ng-token-authangular2-token ..etc 从他们那里我遵循 jtoker auth 因为我想使用 vue.js 。但似乎需要 React 组件才能实现。我在这里附上我使用 Postman 得到的回复。

\n\n

响应正文:

\n\n
{"data":{"id":3,"email":"contact@dazzlebirds.com","provider":"email","uid":"contact@dazzlebirds.com","name":null,"image":null}}\n
Run Code Online (Sandbox Code Playgroud)\n\n

响应头:

\n\n
Cache-Control \xe2\x86\x92max-age=0, private, must-revalidate\nContent-Type \xe2\x86\x92application/json; charset=utf-8\nETag \xe2\x86\x92W/"2af9684eadab13f0efebb27b8e29a7be"\nTransfer-Encoding \xe2\x86\x92chunked\nVary \xe2\x86\x92Origin\nX-Content-Type-Options \xe2\x86\x92nosniff\nX-Frame-Options \xe2\x86\x92SAMEORIGIN\nX-Request-Id \xe2\x86\x9241f3df67-574c-4095-b471-a8fd08b85be5\nX-Runtime \xe2\x86\x920.768768\nX-XSS-Protection \xe2\x86\x921; mode=block\naccess-token \xe2\x86\x92DGoclk9sbb_LRgQrr5akUw\nclient \xe2\x86\x927_Lfy0RlEbzkpLOpiQCKRQ\nexpiry \xe2\x86\x921516322382\ntoken-type \xe2\x86\x92Bearer\nuid \xe2\x86\x92contact@dazzlebirds.com\n
Run Code Online (Sandbox Code Playgroud)\n

Anu*_*yan 5

您需要拦截所有请求/响应调用并包含/检索带有访问令牌的标头。配置标头可以保存在浏览器的本地存储中以维持连接。

您可以使用任何基于 Promise 的 http 客户端来实现此目的,对于下面的示例,我将使用axios

您首先需要在main.jsvue 应用程序文件中导入 axios。

import axios from 'axios'
Run Code Online (Sandbox Code Playgroud)

然后您可以拦截请求

axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.interceptors.request.use(function (config) {
  const authHeaders = JSON.parse(window.localStorage.getItem('authHeaders'))
  if(authHeaders) {
    config.headers[config.method] = {
      'access-token': authHeaders['access-token'],
      'client': authHeaders['client'],
      'uid': authauthHeadersUser['uid']
    }
  }
  return config;
}, function (error) {
  return Promise.reject(error)
});

axios.interceptors.response.use(function (response) {
  if(response.headers['access-token']) {
    const authHeaders = {
      'access-token': response.headers['access-token'],
      'client': response.headers['client'],
      'uid': response.headers['uid'],
      'expiry': response.headers['expiry'],
      'token-type': response.headers['token-type']
    }
    window.localStorage.setItem('authHeaders', JSON.stringify(authHeaders));
  } else {
    window.localStorage.removeItem('authHeaders');
  }
  return response;
}, function (error) {
  return Promise.reject(error)
});
Run Code Online (Sandbox Code Playgroud)