我将前端连接到graphql服务器。大多数(如果不是全部)变异都受到保护,而所有查询均不受保护。我有一个身份验证系统,如果您登录该系统,则会获得一个访问/刷新令牌,所有突变都必须使用。他们做的很棒,后端接收标头和所有内容!
但是。有一个查询至少需要访问令牌才能区分当前用户!但是后端没有收到两个标头!我以为我创建的middlewareLink适用于所有查询/变更,但是我错了,找不到任何其他资源来帮助我。
这是我的设置
apollo-client.js
import { InMemoryCache } from "apollo-cache-inmemory"
import { persistCache } from "apollo-cache-persist"
import { ApolloLink } from "apollo-link"
import { HttpLink } from "apollo-link-http"
import { onError } from "apollo-link-error"
import { setContext } from "apollo-link-context"
if (process.browser) {
try {
persistCache({
cache,
storage: window.localStorage
})
} catch (error) {
console.error("Error restoring Apollo cache", error)
}
}
const httpLink = new HttpLink({
uri: process.env.GRAPHQL_URL || "http://localhost:4000/graphql"
})
const authMiddlewareLink = setContext(() => ({
headers: {
authorization: localStorage.getItem("apollo-token") || null,
"x-refresh-token": localStorage.getItem("refresh-token") || null
}
}))
const afterwareLink = new ApolloLink((operation, forward) =>
forward(operation).map(response => {
const context = operation.getContext()
const {
response: { headers }
} = context
if (headers) {
const token = headers.get("authorization")
const refreshToken = headers.get("x-refresh-token")
if (token) {
localStorage.setItem("apollo-token", token)
}
if (refreshToken) {
localStorage.setItem("refresh-token", refreshToken)
}
}
return response
})
)
const errorLink = onError(({ graphQLErrors, networkError }) => {
...
// really long error link code
...
})
let links = [errorLink, afterwareLink, httpLink]
if (process.browser) {
links = [errorLink, afterwareLink, authMiddlewareLink, httpLink]
}
const link = ApolloLink.from(links)
export default function() {
return {
cache,
defaultHttpLink: false,
link
}
}
是否有一种方法可以使用自定义标头定位所有突变/查询,而不仅仅是突变?还是将一些标头应用于单个查询,因为我可能会将其作为应用中间件?
编辑:还没有解决SSR的部分。一旦我有了答案,便会重新编辑答案。