HTTP POST请求无法解析Next JS 13的响应

mo49yndu  于 2023-04-20  发布在  其他
关注(0)|答案(1)|浏览(144)

我正在尝试向Next JS API路由发送HTTP POST请求。我正在使用Postman发送此请求。此POST请求试图将用户添加到我的Postgres数据库。但是,在保存数据之前,它会在所有字段上进行验证并检查以确保帐户不存在。如果帐户已经存在,则我会得到响应:

{
    "response": "Your account already exists! Please sign in."
}

这是预期的行为。然而,如果帐户不存在,那么Postman只是不断地停留在加载屏幕上,我永远不会得到响应。我已经验证了这不是Postman的问题,因为我已经用Testfully测试过了。下面是我的代码:

import { PrismaClient } from "@prisma/client";
import { NextResponse } from "next/server";
import validator from "validator";
import bcrypt from "bcrypt";
import * as jose from "jose";

const prisma = new PrismaClient();

export async function POST(request: Request) {
  const { firstName, lastName, email, phone, city, password } = await request.json();
  const errors: string[] = [];

  const validationSchema = [
    {
      valid: validator.isLength(firstName, {
        min: 1,
        max: 20,
      }),
      error: "Invalid first name.",
    },
    {
      valid: validator.isLength(lastName, {
        min: 1,
        max: 20,
      }),
      error: "Invalid last name.",
    },
    {
      valid: validator.isEmail(email),
      error: "Invalid email.",
    },
    {
      valid: validator.isMobilePhone(phone),
      error: "Invalid phone number.",
    },
    {
      valid: validator.isLength(city, {
        min: 1,
        max: 20,
      }),
      error: "Invalid city.",
    },
    {
      valid: validator.isStrongPassword(password),
      error: "Invalaid password.",
    },
  ];

  validationSchema.forEach((check) => {
    if (!check.valid) {
      errors.push(check.error);
    }
  });

  if (errors.length) {
    return NextResponse.json(errors[0]);
  }

  const userWithEmail = await prisma.user.findUnique({
    where: {
      email,
    },
  });

  if (userWithEmail) {
    return NextResponse.json({
      response: "Your account already exists! Please sign in.",
    });
  }

  const hash = await bcrypt.hash(password, 22);

  const user = await prisma.user.create({
    data: {
      first_name: firstName,
      last_name: lastName,
      email: email,
      phone: phone,
      city: city,
      password: hash,
    },
  });

  const alg = "HS256";
  const JWTSecret = new TextEncoder().encode(process.env.JWT_SECRET);

  const token = await new jose.SignJWT({
    email: user.email,
  })
    .setProtectedHeader({ alg })
    .setExpirationTime("24h")
    .sign(JWTSecret);

  console.log(token);

  return NextResponse.json({
    JWT: token,
  });
}

编辑:我运行了一堆console.log()```` tests to see where the code is failing and it happens right after prisma create```。没有错误。

mxg2im7a

mxg2im7a1#

从我所看到的测试中,问题在于你对密码的哈希。添加22个salt回合需要大量的时间。将其减少到10个允许服务器在73ms内响应。但是使用22个,需要很长的时间。即使使用15个回合,也需要2秒。Increasing the salt round by 1, doubles the cost.
我建议降低盐轮,或者使用另一种哈希方法。

相关问题