在 ApolloClient 中为每个请求设置授权标头

时间:2021-04-22 17:46:42

标签: next.js apollo-client

我正在通过 Udemy 课程学习 GraphQL 和 Next.js,作者使用 apollo-boost 包中的 ApolloClient。但是@apollo/client 包是新的,我开始使用它。

作者使用 apollo-boost 的 ApolloClient 为每个请求设置凭据,如下所示:

new ApolloClient({
      request: operation => {
        operation.setContext({
          fetchOptions: {
            credentials: 'include'
          },
          headers
        })
      },
      uri: process.env.BASE_URL,
      cache: new InMemoryCache().restore(initialState || {})
})

这对我不起作用,因为@apollo/client 的 ApolloClient 中不存在请求。所以我尝试如下:

const link = new HttpLink({ uri: "http://localhost:3000/graphql", credentials: 'include' });
new ApolloClient({
      cache: new InMemoryCache().restore(initialState || { }),
      link,
    })

但是凭据不适用于每个请求。我没有得到用户信息。 我正在使用将登录用户信息存储在 cookie 中的通行证。 下面是配置passport的index.js文件:

const config = require('../config/dev');
const sessison = require('express-session');
const passport = require('passport');
exports.init = (server, db) => {
  require('./passport').init(passport);
  const sess = {
    name: 'portfolio-session',
    secret: config.SESSION_SECRET,
    cookie: { maxAge: 2 * 60 * 60 * 100},
    resave: false,
    saveUninitialized: false,
    store: db.initSessionStore()
  }

  server.use(sessison(sess));
  server.use(passport.initialize());
  server.use(passport.session());
}

有人可以帮忙编写代码以向 ApolloClient 添加身份验证吗?

谢谢:)

1 个答案:

答案 0 :(得分:0)

从它的外观来看,您实际上并未在示例中传递带有令牌的标头。 以第一作者的例子中传入的标题为例:

[...]
   fetchOptions: {
            credentials: 'include'
          },
          headers // <- this one
        })
      },
[...]

像您尝试做的那样将其添加到请求中:

const link = new HttpLink({ 
  uri: "http://localhost:3000/graphql", 
  headers // <-- pass it here, should contain something along these lines: { Authorization: `Bearer ${token}` } or w/e
});
const client = new ApolloClient({
   cache: new InMemoryCache().restore(initialState || { }),
   link,
});