我尝试将nux.js与apollo结合使用。我必须发送一个授权标头。在我的nuxt.config.js中,请执行以下操作:
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://graphql.fauna.com/graphql',
headers: {
Authorization: 'Bearer xxxxxx'
}
}
}
}
但是尝试进行查询时出现此错误:
“ GraphQL错误:缺少授权头”。
如何发送标题?
最诚挚的问候
答案 0 :(得分:0)
我使用了名为 js-cookie
和
常量令牌= Cookies.get('tokenName')
headers: {
Authorization: token ? `Bearer ${token}` : ''
}
我认为它对我有用
答案 1 :(得分:0)
如果将令牌存储在cookie中,则可以使用tokenName属性指定令牌cookie的名称:
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://graphql.fauna.com/graphql',
tokenName: 'NAME_OF_TOKEN_COOKIE'
}
}
}
它会自动将cookie中的值附加到阿波罗请求中的身份验证标头。
答案 2 :(得分:0)
尽管可能与此有关,但在websockets设置(将lazy
和reconnect
设置为true时,会看到此错误。
原因是注销后,header.authorization
设置为null,这是错误的,应该将整个标头设置为null:
// Return header if token set, else - null
const getHeaders = () => {
const token = store.getters[AuthS.extGetToken]
if (!token) return null
return { authorization: `Bearer ${token}` }
}
// Create a WebSocket link:
const link = new WebSocketLink({
uri: config.backendUrl,
options: {
reconnect: true,
lazy: true,
timeout: 30000,
connectionParams: () => {
return { headers: getHeaders() }
}
}