【问题标题】:Nuxt / Apollo - Set Authorization HeaderNuxt / Apollo - 设置授权标头
【发布时间】:2021-04-07 19:01:04
【问题描述】:

我正在尝试使用nuxtjs 创建登录功能,并在后端使用apollo-server 使用nuxtjs apollo-module 和nodejs。我想将令牌从前端 (nuxtjs/apollo-client) 传递到后端 (nodejs/apollo-server)。


登录功能

async signin () {
  const email = this.email
  const password = this.password
  try {
    const res = await this.$apollo.mutate({
      mutation: signIn,
      variables: {
        email,
        password
      }
    }).then(({ data }) => data && data.signIn)
    const token = res.token
    await this.$apolloHelpers.onLogin(token)
    this.$router.push('/')
  } catch (err) {
    // Error message
  }
}

nuxtjs.config

import Cookies from 'js-cookie'
const token = Cookies.get('apollo-token')

apollo: {  
  clientConfigs: {
    httpEndpoint: 'http://localhost:8000/graphql',
    httpLinkOptions: {
      credentials: 'include',
      headers: {
        'authorization': token ? token : '' // passing the token on this line fails it returns '' 
      }
    }
  }
},

浏览器开发工具中的 Cookie


我无法将令牌传递给授权标头。我也尝试使用 localStorage (`'authorization': (process.client) ? localStorage.getItem('token'`) : ' '`) 来做到这一点,但这似乎是不可能的,因为服务器端渲染。

令牌保存在名为“apollo-token”的 cookie 中。但是,未设置“承载令牌”格式的授权标头。根据 apollo-client 文档,这应该是自动设置的 (https://github.com/nuxt-community/apollo-module#authenticationtype-string-optional-default-bearer)。

我会非常感谢任何帮助!

【问题讨论】:

    标签: graphql apollo apollo-client nuxtjs


    【解决方案1】:

    我遇到了同样的问题, 这很奇怪,一段时间后它开始自动工作 我的配置是

    httpEndpoint: process.env.GRAPHQL_URL,
    httpLinkOptions: {
      credentials: 'same-origin'
    },
    watchLoading: '~/plugins/apollo-watch-loading-handler.js',
    errorHandler: '~/plugins/apollo-error-handler.js',
    wsEndpoint: null, // process.env.STRAPI_GRAPHQL_WS_URL,
    tokenName: 'session-token',
    authenticationType: 'Bearer',
    // Enable Automatic Query persisting with Apollo Engine
    persisting: false,
    // Use websockets for everything (no HTTP)
    // You need to pass a `wsEndpoint` for this to work
    websocketsOnly: false
    

    你也应该将你的配置包装在“默认”中

    apollo: {  
     clientConfigs: {
      default : { 
        httpEndpoint: process.env.GRAPHQL_URL,
        httpLinkOptions: {
         credentials: 'same-origin'
        },
        watchLoading: '~/plugins/apollo-watch-loading-handler.js',
        errorHandler: '~/plugins/apollo-error-handler.js',
        wsEndpoint: null, // process.env.STRAPI_GRAPHQL_WS_URL,
        tokenName: 'session-token',
        authenticationType: 'Bearer',
        persisting: false,
        websocketsOnly: false 
      }
     }
    },
    

    如果这不起作用,请尝试

      // in default config object
      getAuth: () => token ? `Bearer ${token}`: '',
    

    如果有效,请告诉我

    【讨论】:

      猜你喜欢
      • 2020-07-31
      • 2020-10-14
      • 2020-02-21
      • 2021-11-21
      • 2015-12-02
      • 2016-07-13
      • 1970-01-01
      • 1970-01-01
      • 2017-08-31
      相关资源
      最近更新 更多