reactjs - 会话中的 Next-Auth 用户对象为其值返回 null
问题描述
我正在尝试使用 nextjs、next-auth 和 prisma 实现身份验证。我可以成功登录,注销到我的帐户,但对于会话,它不会从 index.tsx 中的代码返回会话
Index.tsx - 我正在从这个文件记录会话对象,它返回一个未定义的值。
import React from 'react';
import { signIn, signOut, useSession } from 'next-auth/client';
export default function index() {
const [session, loading] = useSession();
React.useEffect(() => {
console.log(session); // This returns an undefined value
}, []);
...
}
[...nextauth].ts - 检查用户是否存在于数据库中,并在授权函数中使用 prisma 返回用户值。
export default NextAuth({
providers: [
providers.Credentials({
name: 'Credentials',
credentials: {
email: { label: 'Email', type: 'text', placeholder: 'jsmith' },
password: { label: 'Password', type: 'password' },
},
async authorize(credentials) {
var user = null;
await prisma.user
.findMany({
where: {
email: credentials.email,
password: credentials.password,
},
})
.then((res) => {
if (res) {
user = res;
}
})
.catch((err) => {
throw err;
});
console.log(user);
return user;
},
}),
],
pages: {
signIn: '/login',
},
session: {
jwt: true,
maxAge: 30 * 24 * 60 * 60,
},
secret: process.env.JWT_SECRET,
});
应用程序.tsx
import { Provider } from 'next-auth/client';
import { AppProps } from 'next/app';
const App = ({ Component, pageProps }: AppProps) => {
return (
<Provider session={pageProps.session}>
<Component {...pageProps}></Component>
</Provider>
);
};
export default App;
package.json - 我的环境中的依赖信息。
{
"name": "my-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@prisma/client": "^2.30.3",
"@tailwindcss/forms": "^0.3.3",
"apollo-server-micro": "^3.3.0",
"axios": "^0.21.3",
"cookie": "^0.4.1",
"graphql": "^15.5.2",
"jsonwebtoken": "^8.5.1",
"next": "11.1.2",
"next-auth": "^3.29.0",
"query-string": "^7.0.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"react-hook-form": "^7.15.0"
},
"devDependencies": {
"@types/cookie": "^0.4.1",
"@types/jsonwebtoken": "^8.5.5",
"@types/node": "^16.7.10",
"@types/react": "17.0.19",
"autoprefixer": "^10.3.4",
"eslint": "7.32.0",
"eslint-config-next": "11.1.2",
"postcss": "^8.3.6",
"prisma": "^2.30.3",
"tailwindcss": "^2.2.9",
"ts-node": "^10.2.1",
"typescript": "^4.4.2"
}
}
解决方案
您的控制台日志在会话未完全加载且仅运行一次时运行。在 index.tsx 上
将会话状态添加到 useffect 以在它更改时运行
React.useEffect(() => {
console.log(session);
}, [session]); //Add session state to the useEffect
推荐阅读
- c# - 通过 ASP.NET Core REST API 并发请求后来自 MongoDb 的缓慢响应
- nginx - Certbot HTTP-01 质询失败
- stripe-payments - Plaid + Stripe ACH 集成失败 - account_id 必须是格式正确的非空字符串
- conv-neural-network - 直观理解 CNN 1D 为何适用于表格数据
- node.js - 相同节点模块的系统范围重复数据删除
- php - 在 MySQL 中进行多个不同的动态查询
- at-command - '+CEREG' 未经请求的消息的正常行为是什么?
- awk - 使用 sed 删除两个字符之间的内容,但到那时为止,如果该字符再次出现,则直到最后
- r - 我需要在我的数据集中创建一个新变量。它由 r 中两个现有变量的条件定义
- xslt - 在 Streaming XSLT 中使用同一个节点两次