Liz*_*Liz 6 javascript sqlite node.js server prisma
我将此控制台日志放在这里以查看接收的内容:\n{\n用户名:'aa',\ngender:'Feminino',\n货物:'2',\nemail:'a',\n密码:'a'\n }\n这是我遇到的错误消息:
\nPrisma client error: {\n timestamp: 2023-07-22T15:07:56.078Z,\n message: '\\n' +\n 'Invalid `prisma.user.findUnique()` invocation in\\n' +\n 'C:\\\\Users\\\\luiza\\\\Documents\\\\autentica\xc3\xa7\xc3\xa3o\\\\server.js:19:46\\n' +\n '\\n' +\n ' 16 password,\\n' +\n ' 17 });\\n' +\n ' 18 try {\\n' +\n '\xe2\x86\x92 19 const existingUser = await prisma.user.findUnique({\\n' +\n ' where: {\\n' +\n ' email: "a",\\n' +\n ' ? id?: Int,\\n' +\n ' ? AND?: UserWhereInput | UserWhereInput[],\\n' +\n ' ? OR?: UserWhereInput[],\\n' +\n ' ? NOT?: UserWhereInput | UserWhereInput[],\\n' +\n ' ? gender?: StringFilter | String,\\n' +\n ' ? password?: StringFilter | String,\\n' +\n ' ? username?: StringNullableFilter | String | Null,\\n' +\n ' ? admin?: BoolFilter | Boolean,\\n' +\n ' ? created_at?: DateTimeFilter | DateTime,\\n' +\n ' ? cargoId?: IntNullableFilter | Int | Null,\\n' +\n ' ? refreshTokens?: RefreshTokenListRelationFilter,\\n' +\n ' ? cargo?: CargoNullableRelationFilter | CargoWhereInput | Null,\\n' +\n ' ? posts?: PostListRelationFilter,\\n' +\n ' ? comments?: CommentListRelationFilter\\n' +\n ' }\\n' +\n ' })\\n' +\n '\\n' +\n 'Argument `where` of type UserWhereUniqueInput needs at least one of `id` arguments. Available options are listed in green.',\n target: 'user.findUnique'\n}\nErro: PrismaClientValidationError:\nInvalid `prisma.user.findUnique()` invocation in\n 16 password,\n 17 });\n 18 try {\n\xe2\x86\x92 19 const existingUser = await prisma.user.findUnique({\n where: {\n email: "a",\n ? id?: Int,\n ? AND?: UserWhereInput | UserWhereInput[],\n ? OR?: UserWhereInput[],\n ? NOT?: UserWhereInput | UserWhereInput[],\n ? gender?: StringFilter | String,\n ? password?: StringFilter | String,\n ? username?: StringNullableFilter | String | Null,\n ? admin?: BoolFilter | Boolean,\n ? created_at?: DateTimeFilter | DateTime,\n ? cargoId?: IntNullableFilter | Int | Null,\n ? refreshTokens?: RefreshTokenListRelationFilter,\n ? cargo?: CargoNullableRelationFilter | CargoWhereInput | Null,\n ? posts?: PostListRelationFilter,\n ? comments?: CommentListRelationFilter\n }\n })\nRun Code Online (Sandbox Code Playgroud)\n客户端:
\ndocument.addEventListener('DOMContentLoaded', () => {\n const createAccountBtn = document.getElementById('createAccountBtn');\n const loginBtn = document.getElementById('loginBtn');\n const cargoInput = document.getElementById('cargoInput');\n const nucleoSelection = document.getElementById('nucleoSelection');\n\n if (createAccountBtn) {\n createAccountBtn.addEventListener('click', handleCreateAccount);\n }\n\n if (loginBtn) {\n loginBtn.addEventListener('click', handleLogin);\n }\n\n cargoInput.addEventListener('change', () => {\n const selectedCargo = cargoInput.value;\n // Check if "L\xc3\xadder de N\xc3\xbacleo" or "Membro" is selected, and show or hide the additional selection box accordingly\n if (selectedCargo === 'lider de nucleo' || selectedCargo === 'membro') {\n nucleoSelection.style.display = 'block';\n } else {\n nucleoSelection.style.display = 'none';\n }\n });\n});\n\nasync function handleCreateAccount(event) {\n event.preventDefault();\n\n const nameInput = document.getElementById('nameInput').value;\n const genderInput = document.getElementById('genderInput').value;\n const cargoInput = document.getElementById('cargoInput').value;\n const nucleoInput = document.getElementById('nucleoInput').value; // Get the selected nucleo value if applicable\n const emailInput = document.getElementById('emailInput').value;\n const passwordInput = document.getElementById('passwordInput').value;\n const genderValue = document.getElementById('genderValue');\n genderValue.value = genderInput;\n\n try {\n const response = await fetch('http://localhost:3000/register', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n username: nameInput,\n gender: genderInput,\n cargo: cargoInput,\n nucleo: nucleoInput, // Pass the selected nucleo value if applicable\n email: emailInput,\n password: passwordInput,\n }),\n });\n\n const data = await response.json();\n if (response.ok) {\n alert(data.message);\n redirectToFeed();\n } else {\n alert(data.error);\n }\n } catch (error) {\n console.error('Erro durante o registro:', error);\n alert('Falha no registro.');\n }\n}\n\nasync function handleLogin() {\n const emailInput = document.getElementById('emaillogin').value;\n const passwordInput = document.getElementById('senhalogin').value;\n\n try {\n const response = await fetch('http://localhost:3000/login', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n email: emailInput,\n password: passwordInput,\n }),\n });\n\n const data = await response.json();\n if (response.ok) {\n // Store the JWT token received from the server securely (e.g., in local storage)\n localStorage.setItem('jwtToken', data.token);\n alert(data.message);\n setTimeout(() => {\n // Clear the input fields after a second\n document.getElementById('emaillogin').value = '';\n document.getElementById('senhalogin').value = '';\n }, 1000);\n redirectToFeed();\n } else {\n alert(data.error);\n }\n } catch (error) {\n console.error('Erro durante o login:', error);\n alert('Falha no login.');\n }\n}\n\nfunction redirectToFeed() {\n window.location.href = '/feedlogado.html';\n}\n\nRun Code Online (Sandbox Code Playgroud)\n服务器端:
\nconst express = require('express');\nconst { PrismaClient } = require('@prisma/client');\nconst bcrypt = require('bcrypt');\nconst jwt = require('jsonwebtoken');\nconst app = express();\nconst cors = require('cors');\nconst prisma = new PrismaClient();\napp.use(cors());\napp.use(express.json());\n\nconst jwtSecret = 'yourSecretKey';\nconst user = await db.collection('users').where('id', userId).get();\nfunction generateToken(user) {\n return jwt.sign({ userId: user.id }, jwtSecret, { expiresIn: '8h' }); // Token expires in 8 hours\n}\n\napp.post('/login', async (req, res) => {\n const { email, password } = req.body;\n\n try {\n const user = await prisma.user.findUnique({\n where: { email: email },\n select: { id: true, email: true, password: true },\n });\n\n if (!user) {\n return res.status(401).json({ error: 'Credenciais inv\xc3\xa1lidas' });\n }\n const passwordMatch = await bcrypt.compare(password, user.password);\n\n if (passwordMatch) {\n const token = generateToken(user);\n return res.status(200).json({ message: 'Login realizado com sucesso!', token, id: user.id, email: user.email });\n } else {\n return res.status(401).json({ error: 'Credenciais inv\xc3\xa1lidas' });\n }\n } catch (error) {\n console.error('Erro durante o login:', error);\n res.status(500).json({ error: 'Login falhou' });\n }\n});\n\napp.post('/register', async (req, res) => {\n const { username, gender, cargo, nucleo, email, password } = req.body;\n\n try {\n const existingUser = await prisma.user.findUnique({\n where: { email },\n });\n\n if (existingUser) {\n return res.status(409).json({ error: 'Email already exists' });\n }\n const hashedPassword = await bcrypt.hash(password, 10);\n\n const existingCargo = await prisma.cargo.findUnique({ where: { name: cargo } });\n\n if (!existingCargo) {\n return res.status(404).json({ error: 'Cargo not found' });\n }\n\n let nucleoConnect;\n if (nucleo && !isNaN(parseInt(nucleo))) {\n const existingNucleo = await prisma.nucleo.findUnique({ where: { id: parseInt(nucleo) } });\n if (!existingNucleo) {\n return res.status(404).json({ error: 'Nucleo not found' });\n }\n nucleoConnect = { connect: { id: existingNucleo.id } };\n }\n\n const newUser = await prisma.user.create({\n data: {\n username,\n gender,\n cargo: {\n connect: { id: existingCargo.id },\n },\n nucleo: nucleoConnect,\n email,\n password: hashedPassword,\n },\n });\n\n res.status(200).json({ message: 'Conta criada com sucesso!' });\n } catch (error) {\n console.error('Erro:', error);\n res.status(500).json({ error: 'Registro falhou.' });\n }\n});\n\n\nconst port = process.env.PORT || 3000;\n\nconst server = app.listen(port, () => {\n console.log(`Servidor iniciado em http://localhost:${port}`);\n});\n\nprocess.on('SIGINT', () => {\n console.log('Received SIGINT. Closing server...');\n server.close(() => {\n console.log('Server closed.');\n prisma.$disconnect().then(() => {\n console.log('Prisma client disconnected.');\n process.exit(0);\n });\n });\n});\n\nprisma.$on('error', (err) => {\n console.error('Prisma client error:', err);\n});\n\nRun Code Online (Sandbox Code Playgroud)\n另外,如果有帮助的话,这是我的棱镜模型:
\ngenerator client {\n provider = "prisma-client-js"\n}\n\ndatasource db {\n provider = "sqlite"\n url = "file:./database.db"\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n gender String \n password String \n username String? \n email String @unique\n refreshTokens RefreshToken[]\n admin Boolean @default(false)\n created_at DateTime @default(now())\n \n cargo Cargo? @relation(fields: [cargoId], references: [id])\n cargoId Int?\n\n posts Post[]\n comments Comment[]\n}\n\nmodel Cargo {\n id Int @id @default(autoincrement())\n nome String \n nucleo String \n created_at DateTime @default(now())\n\n users User[]\n}\n\nmodel Post {\n id Int @id @default(autoincrement())\n content String\n updated_at DateTime @updatedAt\n created_at DateTime @default(now())\n\n comment Comment[]\n\n userId Int\n user User @relation(fields: [userId], references: [id])\n}\n\nmodel Comment {\n\n id Int @id @default(autoincrement()) \n content String\n\n postId Int\n post Post @relation(fields: [postId], references: [id])\n\n userId Int\n user User @relation(fields: [userId], references: [id])\n \n} \nmodel RefreshToken {\n id Int @id @default(autoincrement())\n hashedToken String\n userId Int \n User User @relation(fields: [userId], references: [id], onDelete: Cascade)\n revoked Boolean @default(false)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n}\nRun Code Online (Sandbox Code Playgroud)\n我已经尝试检查它的收集是否正确,但我找不到问题所在(仍在学习)
\n小智 4
'Argument `where` of type UserWhereUniqueInput needs at least one of `id` arguments. Available options are listed in green.'
Run Code Online (Sandbox Code Playgroud)
从你的堆栈跟踪中,我收集到的是 Prisma 不知道电子邮件字段是唯一的。你的查询看起来不错。所以我认为你的问题是你需要重新生成你的 prisma 客户端。
根据我使用 Prisma 的经验,有时将架构更改推送到数据库后,客户端不会自动重新生成。
尝试:prisma generate在你的终端中。