在响应标头中设置Cookie,但未在浏览器中设置

时间:2018-11-24 07:00:51

标签: typescript express cookies graphql apollo-server

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

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

但是在Chrome的“存储”>“ 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
    },

1 个答案:

答案 0 :(得分:0)

您是否在客户端使用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