简体   繁体   English

使用 Next.js 将新用户添加到数据库时出错 | 棱镜 | Heroku

[英]Error adding New User to database with Next.js | Prisma | Heroku

I'm working on my first full-stack app project following along with an online course.我正在开发我的第一个全栈应用程序项目以及在线课程。 I've hit a roadblock that I've been unable to resolve after hours of troubleshooting.经过数小时的故障排除后,我遇到了无法解决的障碍。 The error occurs when attempting to add a new user to a Postgres DB via the command line.尝试通过命令行将新用户添加到 Postgres DB 时发生错误。

import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'
import cookie from 'cookie'
import { NextApiRequest, NextApiResponse } from 'next'
import prisma from '../../lib/prisma'

export default async (req: NextApiRequest, res: NextApiResponse) => {
    const salt = bcrypt.genSaltSync()
    const { email, password } = req.body

    let user

    try {
        user = await prisma.user.create({
            data: {
            email,
            password: bcrypt.hashSync(password, salt),
        },
      })
    } catch (e) {
      res.status(401)
      res.json({ error: 'User already exists' })
      return
    }

    const token = jwt.sign(
    {
      email: user.email,
      id: user.id,
      time: Date.now(),
    },
      'hello',
      { expiresIn: '8h' }
    )

  res.setHeader(
    'Set-Cookie',
    cookie.serialize('TRAX_ACCESS_TOKEN', token, {
      httpOnly: true,
      maxAge: 8 * 60 * 60,
      path: '/',
      sameSite: 'lax',
      secure: process.env.NODE_ENV === 'production',
    })
  )

  res.json(user)
}

I am attempting to add the user with the below command via HTTPie:我正在尝试通过 HTTPie 使用以下命令添加用户:

http POST :3000/api/signup email=h@h.com password=abcabc

I was getting an error on the data attribute that was resolved after running 'prisma generate'.我在运行“prisma generate”后得到解决的数据属性错误。

However, I am still getting an error: User already exists.但是,我仍然收到一个错误:用户已经存在。

I can verify the user does not exist by checking the Prisma Studio in the Users table and there is no new user created.我可以通过检查用户表中的 Prisma Studio 来验证用户不存在,并且没有创建新用户。

Response:回复:

HTTP/1.1 401 Unauthorized
Connection: keep-alive
Content-Length: 31
Content-Type: application/json; charset=utf-8
Date: Sun, 05 Jun 2022 19:57:59 GMT
ETag: "1f-lFUySNKwX3L5eGEwGcNcUoVKWhE"
Keep-Alive: timeout=5
Vary: Accept-Encoding

{
    "error": "User already exists"
}

This is my schema.prisma file:这是我的 schema.prisma 文件:

    // This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider          = "postgresql"
  url               = env("DATABASE_URL")
  shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}

model User {
  id        Int        @id @default(autoincrement())
  createdAt DateTime   @default(now())
  updatedAt DateTime   @updatedAt
  email     String     @unique
  firstName String?
  lastName  String?
  password  String
  playlists Playlist[]
}

model Song {
  id        Int        @id @default(autoincrement())
  createdAt DateTime   @default(now())
  updatedAt DateTime   @updatedAt
  name      String
  artist    Artist     @relation(fields: [artistId], references: [id])
  artistId  Int
  playlists Playlist[]
  duration  Int
  url       String
}

model Artist {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  songs     Song[]
  name      String   @unique
}

model Playlist {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  name      String
  songs     Song[]
  user      User     @relation(fields: [userId], references: [id])
  userId    Int
}

I was able to get this working by updating my middleware.ts to include the prefix ${origin} like so:我可以通过更新我的 middleware.ts 以包含前缀 ${origin} 来完成这项工作,如下所示:

import { NextResponse } from 'next/server'

const signedinPages = ['${origin}/', '${origin}/playlist', 
'${origin}/library']

export default function middleware(req) {
  if (signedinPages.find((p) => p === req.nextUrl.pathname)) {
    const token = req.cookies.MMA_ACCESS_TOKEN

    if (!token) {
      return NextResponse.redirect('${origin}/signin')
    }
  }
}

and my HTTPie request to和我的 HTTPie 请求

http POST :3000/api/signup email=h@h.com password=abcabc firstName=Eric lastName=Bell

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM