【问题标题】:Nuxt appolo module How to send authorization header?Nuxt appolo 模块如何发送授权标头?
【发布时间】:2020-06-07 22:57:56
【问题描述】:
我尝试将 nux.js 与 apollo 一起使用。我必须发送一个授权标头。在我的 nuxt.config.js 中试试这个:
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://graphql.fauna.com/graphql',
headers: {
Authorization: 'Bearer xxxxxx'
}
}
}
}
但是当我尝试进行查询时出现此错误:
“GraphQL 错误:缺少授权标头”。
如何发送标头?
最好的问候
【问题讨论】:
标签:
graphql
nuxt.js
apollo
faunadb
【解决方案1】:
在设置 websockets 时看到此错误(lazy 和 reconnect 设置为 true),但可能与此有关。
原因是注销后header.authorization被设置为null,这是错误的,整个header应该被设置为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() }
}
}
【解决方案2】:
如果您将令牌存储在 cookie 中,您可以使用 tokenName 属性来指定令牌 cookie 的名称:
apollo: {
clientConfigs: {
default: {
httpEndpoint: 'https://graphql.fauna.com/graphql',
tokenName: 'NAME_OF_TOKEN_COOKIE'
}
}
}
它会自动将 cookie 中的值附加到 apollo 请求中的身份验证标头。
【解决方案3】:
我使用了名为 js-cookie 的包和
const token = Cookies.get('tokenName')
headers: {
Authorization: token ? `Bearer ${token}` : ''
}
我认为它对我有用