使用withCredentials选项可以确保浏览器发送和接收cookies。在将Apollo Client添加到应用程序中时,应使用withCredentials选项进行配置。
例如:
const client = new ApolloClient({ uri: '/graphql', fetchOptions: { credentials: 'include', }, });
服务端应该返回带有Set-Cookie头的响应,以便浏览器将其视为有效的cookie。
例如:
app.use(cookieParser()); app.use('/graphql', bodyParser.json(), cookieParser(), graphqlExpress(req => { return { schema, context, }; }));
如果接收方域或路径不正确,则在发送cookie时可能会遇到问题。在客户端和服务器端都应该检查域名和路径是否正确匹配。
例如:
客户端:
const client = new ApolloClient({ uri: '/graphql', credentials: 'include', });
服务器端:
app.use(cookieParser()); app.use('/graphql', bodyParser.json(), cookieParser(), graphqlExpress(req => { return { schema, context, }; }));
请注意,URI 和派生从 URI 的所有字段(例如'路径”)像个人博客一样匹配。例如,'http:// localhost:3000 / graphql”与'http:// localhost:3000 / graphql /”是不同的。
当然,还可以采取其他措施来确保cookie是正常工作的。将上面的建议与以下的最佳实践一起使用可以确保cookie以最佳方式运行。