在使用Apollo GraphQL应用程序时,可以使用以下代码示例来设置Cookie:
在服务端设置:
const server = new ApolloServer({
context: ({ req, res }) => {
res.cookie('cookieName', 'cookieValue', {
maxAge: 1000 * 60 * 60 * 24 * 7, // 7 days
httpOnly: false, // set to true if you want to disable access from client-side JavaScript
secure: process.env.NODE_ENV === 'production', // set to true if you want to enable secure cookies (requires HTTPS)
sameSite: 'lax', // set to 'strict' if you want to disable cross-site requests
});
return { req, res };
},
// other Apollo Server options
});
在客户端设置:
const client = new ApolloClient({
link: createHttpLink({
uri: 'http://localhost:4000/graphql',
credentials: 'include',
}),
cache: new InMemoryCache(),
// other Apollo Client options
});
请注意,客户端代码中的“credentials”选项必须设置为“include”,以便发送Cookie。而“credentials”选项在服务端配置上不需要设置。
在设置Cookie时,请注意安全和跨站请求的设置。