alt*_*tF4 3 javascript cookies graphql apollo-client
所以我有一个在 运行的 Express / TypeGraphql 后端localhost:5000,在 运行的 Next / React 应用程序localhost:3000。我决定使用 apollo-server 作为 graphql API,使用 apollo-client 作为前端。成功登录后,我将 httpOnly cookie 存储在网络浏览器中。
我想要做的是,在每个请求中获取 cookie,并在 oauth2 令牌有效的情况下向用户授权。即使请求有效,并且我收到查询,cookie 也显示为空。另外,我在控制台中没有收到任何错误。
\n这里我保存cookies =>
\napp.get('/auth/google/callback', function (req, res, next) {\n passport.authenticate('google', { session: false }, (err, user, info) => {\n if (err) return next(err);\n if (!user) return res.redirect('/');\n res.cookie('login_cookie', JSON.stringify(info), {\n secure: false,\n httpOnly: true,\n expires: dayjs().add(30, 'days').toDate(),\n sameSite: false,\n });\n return res.redirect('http://localhost:3000/home');\n })(req, res, next);\n});\nRun Code Online (Sandbox Code Playgroud)\n在这里,我在请求后将 cookie 记录到控制台=>
\n@Query(() => [User])\nasync users(@Ctx() ctx: Context) {\n console.log('cookies ', ctx.req.cookies);\n return await ctx.prisma.user.findMany();\n}\nRun Code Online (Sandbox Code Playgroud)\n最后,这是我的 apollo 客户端配置 =>
\nconst client = new ApolloClient({\n cache: new InMemoryCache(),\n credentials: "include",\n uri: "http://localhost:5000/graphql",\n});\nRun Code Online (Sandbox Code Playgroud)\n每次请求后,我的控制台都会显示cookies: [Object: null prototype] {},即使我在浏览器的 cookie 存储中看到它们。
export async function getServerSideProps() {\nconst { data } = await client.query({\n query: gql`\n query allUsers {\n users {\n id\n username\n }\n }\n `,\n});\n\nreturn {\n props: {\n users: data.users,\n },\n};\nRun Code Online (Sandbox Code Playgroud)\n}
\nHer*_*rku 10
我认为你还没有完全理解 Next.js。Next.js 在服务器上渲染视图,或者将“服务器端 props”发送到客户端。这意味着getServerSideProps在服务器上执行(顾名思义)。Cookie 是浏览器的一项功能。那么会发生什么呢?
getServeSideProps。这意味着您必须首先确保您的 Next.js 服务器从前端接收 cookie。如果它与 GraphQL 服务器位于同一源,这应该会自动发生。否则,这有点棘手,在这种情况下使用显式授权标头应该更容易。然后你必须将 cookie 与请求一起传递。req这可以通过访问ingetServerSiteProps并使用contextin来完成client.query。
export async function getServerSideProps(context) {
const Cookie = context.req.headers.cookie;
const { data } = await client.query({
context: { headers: { Cookie } },
query: gql`
query allUsers {
users {
id
username
}
}
`,
});
return {
props: {
users: data.users,
},
};
}
Run Code Online (Sandbox Code Playgroud)
代码未经测试,但我想您已经明白了。
| 归档时间: |
|
| 查看次数: |
1935 次 |
| 最近记录: |