I built a GraphQL server using apollo-server-express
, and run it on localhost:4000.
When I pass the query from GraphQL playground, the response has set-cookie in the header as below: response header
But in storage > cookies tab in chrome, there are no cookies. chrome: application > storage > cookies
Here is my server.ts. (I think I set my cors
config in correct way)
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 }
And here is my 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
},
Are you using apollo-client on the client side?
If so, you need to add the credentials
option when you create the terminating http link (or batch link etc). If not using apollo-client, you just need to add in this option accordingly.
const OPTS = {
uri: GQL_BASE,
credentials: 'include', // or 'same-origin' etc.
includeExtensions: true,
}
const httpLink = new BatchHttpLink(OPTS)
You are correct, that you also need credentials: true
added in the CORS options.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.