【发布时间】: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 ''
}
}
}
},
我无法将令牌传递给授权标头。我也尝试使用 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