【问题标题】:How to forward response headers through GraphQL to client如何通过 GraphQL 将响应标头转发给客户端
【发布时间】:2019-05-22 02:58:06
【问题描述】:

我在使用 GraphQL 时遇到问题,在返回客户端时响应标头被丢弃。我的应用程序使用 NodeJS、Passport.js 和 Express Cookie-Session 来管理身份验证和会话。

我有一个现有的 /login 路由,它通过 Passport 进行身份验证并将 user{} 对象和 set-cookie 标头返回给客户端。结果,在客户端的浏览器上创建了一个 cookie,并建立了它们的会话。

现在,我们最近添加了 GraphQL,我创建了一个 login 查询,它调用现有的 /login 路由并以 user{} 对象响应。但是,当 GraphQL 将响应返回给客户端时,不再包含响应​​标头,因此永远不会创建 cookie。

如何通过 GraphQL 将原始响应标头转发到客户端?

以下是 GraphQL 登录示例:

login { 
  type: typeLogin,
  args : { 'username/password here' },
  async resolve(_, args, context) {
    const response = await fetch('/login', {
      credentials: 'include',
      method: 'POST',
      body: JSON.stringify('username/password here')
   })

   const data = await response.json();

   // console.log(response.headers) will display correct headers

   return data; // User is returned but response headers are not
   }
 }

【问题讨论】:

    标签: node.js graphql passport.js


    【解决方案1】:

    我已经这样做了,

    链接:https://github.com/masmerino13/graphql-backend/blob/master/src/resolvers/Mutations/UserMutation.js#L31

    让我知道这是否适合你

    问候!

    【讨论】:

    • 谢谢,这有助于展示如何在 GraphQL 响应中创建 cookie。但是,在我的例子中,cookie 是在 Node 端点内创建的,需要通过 GraphQL 转发到客户端。 GraphQL 基本上是一个将 cookie 转发给用户的中间人。
    • 是的,你测试过这样的东西吗? context.res.set('cookie', cookieValue); 参考:github.com/graphql/express-graphql/issues/71
    猜你喜欢
    • 2018-02-14
    • 1970-01-01
    • 2019-07-26
    • 2019-07-26
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2020-03-31
    相关资源
    最近更新 更多