我正在尝试使用 nuxtjs 与 nuxtjs apollo-module 和 nodejs 在后端使用 apollo-server 创建登录功能。我想将令牌从前端(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 ''
}
}
}
},
令牌保存在名为“apollo-token”的 cookie 中。但是,未设置“承载令牌”格式的授权标头。根据 apollo-client 文档,这应该自动设置(https://github.com/nuxt-community/apollo-module#authenticationtype-string-optional-default-bearer)。
我将非常非常感谢任何形式的帮助!
我遇到了同样的问题, 这很奇怪,一段时间后它开始自动工作 我的配置是
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}`: '',
如果有效请告诉我
autoImports: true,
authType: 'Bearer',
authHeader: 'Authorization',
tokenStorage: 'cookie',
proxyCookies: true,
clients: {
default: {
httpEndpoint: `${process.env.APPLICANT_URL}/graphql`,
tokenStorage: 'cookie',
tokenName: "apollo:default.token",
httpLinkOptions: {
credentials: 'include'
}
}
}