【问题标题】:Set-cookie in response header but not set in browser在响应标头中设置 cookie,但未在浏览器中设置
【发布时间】:2019-04-26 14:41:52
【问题描述】:

我使用apollo-server-express 构建了一个 GraphQL 服务器,并在 localhost:4000 上运行它。

当我从 GraphQL 操场传递查询时,响应的标头中有 set-cookie,如下所示: response header

但在 chrome 的 storage > cookies 标签中,没有 cookie。 chrome: application > storage > cookies

这是我的 server.ts。 (我想我以正确的方式设置了我的 cors 配置)

const server = new ApolloServer({
  typeDefs,
  resolvers,
  introspection: true,
  playground: true,
  dataSources: () => ({
    projectAPI: new ProjectAPI(),
  }),
  context: ({ req, res }: { req: Request; res: Response }) => ({ req, res }),
})

const app = express()

/* Parse cookie header and populate req.cookies */
app.use(cookieParser())

app.use(
  cors({
    origin: '*',
    credentials: true, // <-- REQUIRED backend setting
  })
)

app.use((req: any, res: any, next: any) => {
    console.log(req.cookies)
    next()
})

server.applyMiddleware({ app, path: '/' })

if (process.env.NODE_ENV !== 'test') {
  app.listen({ port: 4000 }, () =>
    console.log(`???? Server ready at http://localhost:4000${server.graphqlPath}`)
  )
}

export { server }

这是我的resolvers.ts

export default {
  Query: {
    session: async (_: null | undefined, __: null | undefined, { res }: any) => {
      const response = await fetch(`http://localhost:3000/api/v1/sessions/current_user`, {
        headers: {
          'content-type': 'application/json',
        },
      })

      /** Get session cookie from the response header */
      const sessionCookie = setCookie
        .parse(response.headers.get('set-cookie') as string)
        .find((el: any) => el.name === '_session')

      /** If session cookie exists, save the cookie */
      if (sessionCookie && res) {
        const { name, value, ...rest } = sessionCookie
        res.cookie(name, value, rest)
      }

      const data = await response.json()
      return data.user
    },

【问题讨论】:

    标签: typescript express cookies graphql apollo-server


    【解决方案1】:

    你在客户端使用 apollo-client 吗?

    如果是这样,您需要在创建终止 http 链接(或批处理链接等)时添加 credentials 选项。如果不使用 apollo-client,您只需要相应地添加此选项。

    const OPTS = {
      uri: GQL_BASE,
      credentials: 'include', // or 'same-origin' etc.
      includeExtensions: true,
    }
    
    const httpLink = new BatchHttpLink(OPTS)
    

    你是对的,你还需要在 CORS 选项中添加credentials: true

    【讨论】:

      猜你喜欢
      • 2014-08-24
      • 2020-10-07
      • 2012-05-02
      • 2021-07-20
      • 2016-10-30
      • 1970-01-01
      • 2018-10-26
      • 2019-04-01
      • 2019-11-12
      相关资源
      最近更新 更多