peterlits zo
Posted on March 7, 2022
Why
In this post, I am using apollo client to send GraphQL request in the front-end.
It time to deal with those request and return a response in the back-end.
To do it, we choose express (a JavaScript web framework) as a server.
What's the question?
Well. To deal with the GraphQL request, the best idea is using express-graphql. But it does not have the interface to set cookie to get the authorization.
// init a express server
const GraphQLServer = express();
// deal with the GraphQL request with graphqlHTTP,
// which is from the express-graphql.
GraphQLServer.use(
"/graphql",
graphqlHTTP({
schema: GraphQLSchema,
graphiql: GRAPHIQL,
})
);
// Listen to port 4000.
GraphQLServer.listen(4000, () => {
console.log("Listening on localhost:4000...");
});
Now we do not have idea.
Solution
The solution is that send the req
and res
into the graphqlHTTP
's context:
GraphQLServer.use(
"/graphql",
// The returned value of graphqlHTTP is also a function.
// We just add a wrapper to set its context.
(req, res) => {
return graphqlHTTP({
schema: GraphQLSchema,
graphiql: GRAPHIQL,
context: { req, res },
})(req, res)
})
);
Click for more information: https://stackoverflow.com/questions/46023367/graphql-issuing-jwt-cookie
đź’– đź’Ş đź™… đźš©
peterlits zo
Posted on March 7, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.