在来自 comments 的一些建议之后更新了代码(仍然收到相同的错误):

const bcrypt = require("bcrypt")
const User = require("../../model/userModel")

export async function POST(req: NextRequest) {
  await dbConnect()
  const res = await req.json()
  await bcrypt.hash(res.passwd, 10)
      .then(async (hashedPassword: any) => {
          //create a new user instance and collect the data
          const user = new User({
              firstname: res.firstname,
              lastname: res.lastname,
              company: res.company,
              phone: res.phone,
              email: res.email,
              password: hashedPassword,
          })
          await user.save()
          //return succes if the new user is added to the database
          .then((result: string) => {
              return NextResponse.json({message: "User created successfully "},{status : 201}) 
          })
          .catch((err: string) => {
            console.log("error" + err)
            return NextResponse.json({message: "Error creating user :"},{status : 500}) 
          })
      })
      .catch((err: string) => {
        console.log("error" + err)
        return NextResponse.json({message: "Password was not hashed successfully "},{status : 500})  
      })
}

我找不到为什么会出现这个错误:

  TypeError: Cannot read properties of undefined (reading 'headers')
    at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:265:61)    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

我也看到过类似的错误,但这个问题的答案是返回NextResponse.json().我已经在这样做了,但我仍然收到错误.

这是我调用POST请求的地方:

async function createUser(ev: any){
        ev.preventDefault()
        const data = {firstname, lastname, company, phone, email, passwd}
        await axios.post("./api/register", data)
    }

    //Email validation
    function isValidEmail(email: string) {
        return /\S+@\S+\.\S+/.test(email);
      }
      

  return (
    <>
        <main className="flex justify-center items-center w-screen min-h-screen bg-[url('../public/bg-login.jpg')] bg-no-repeat bg-cover">
            <div className="flex flex-col w-1/2 h-3/4 rounded-lg shadow-2xl shadow-white m-5">
                <form onSubmit={createUser} className="w-full"> 
                    <div className="grid sm:grid-cols-1 md:grid-cols-2 gap-10 mb-5 mr-5 ml-5 mt-5">
                        <div>
                            <label htmlFor="firstname" className="text-white block mb-2 text-sm font-medium dark:text-white">*First name</label>
                            <input 
                                className="outline-none bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:border-blue-500 p-2 w-full" 
                                type="text"
                                onChange={ (e) => {
                                setFirstname(e.target.value)
                                }}
                                placeholder="First name"
                                value={firstname} 
                                id="firstname"
                                required/>
                        </div>
                        <div>
                            <label htmlFor="lastname" className="text-white block mb-2 text-sm font-medium dark:text-white">*Last name</label>
                            <input 
                                className="outline-none bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:border-blue-500 p-2 w-full" 
                                type="text"
                                onChange={ (e) => {
                                setLastname(e.target.value)
                                }}
                                placeholder="Last name"
                                value={lastname} 
                                id="lastname"
                                required/>
                        </div>
                        <div>
                            <label htmlFor="company" className="text-white block mb-2 text-sm font-medium dark:text-white">*Company</label>
                            <input 
                                className="outline-none bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:border-blue-500 p-2 w-full" 
                                type="text"
                                onChange={ (e) => {
                                setCompany(e.target.value)
                                }}
                                placeholder="Zincometal"
                                value={company} 
                                id="company"
                                required/>
                        </div>
                        <div>
                            <label htmlFor="phone" className="text-white block mb-2 text-sm font-medium dark:text-white">*Phone number</label>
                            <input 
                                className="outline-none bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:border-blue-500 p-2 w-full" 
                                type="number"
                                onChange={ (e) => 
                                    {  
                                        setPhone(e.target.valueAsNumber)       
                                    }}
                                placeholder="xx-xxx-xxx-xx"
                                value={phone} 
                                id="phone"
                                required/>
                        </div>
                        <div className="md:col-span-2 sm:col-span-1">
                            <label htmlFor="email" className="text-white block mb-2 text-sm font-medium dark:text-white">*Email Address</label>
                            <input 
                                className="outline-none bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:border-blue-500 p-2 w-full" 
                                type="text"
                                onChange={ (e) => 
                                    {  
                                        if (!isValidEmail(e.target.value)){
                                            setError(true)
                                        }else{
                                            setError(false)
                                        }
                                        setEmail(e.target.value)       
                                    }}
                                placeholder="example@hotmail.com"
                                value={email} 
                                id="email"
                                required/>
                        </div>
                        <div className="md:col-span-2 sm:col-span-1">
                            <label htmlFor="passwd" className="text-white block mb-2 text-sm font-medium dark:text-white">*Password</label>
                            <input 
                                className="outline-none bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:border-blue-500 p-2 w-full" 
                                type="password"
                                onChange={ (e) => 
                                    {  
                                            setPasswd(e.target.value)       
                                    }}
                                placeholder="*******"
                                value={passwd} 
                                id="passwd"
                                required/>
                        </div>
                        <div className="md:col-span-2 sm:col-span-1">
                            <label htmlFor="confPasswd" className="text-white block mb-2 text-sm font-medium dark:text-white">*Confirm Password</label>
                            <input 
                                className="outline-none bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:border-blue-500 p-2 w-full" 
                                type="password"
                                onChange={ (e) => 
                                    {  
                                            setConfPasswd(e.target.value)       
                                    }}
                                placeholder="*******"
                                value={confPasswd} 
                                id="confPasswd"
                                required/>
                        </div>
                        <div className="flex items-start">
                            <div className="flex items-center h-6">
                                <input
                                    className="w-4 h-4 border border-gray-300 rounded bg-gray-50 focus:ring-3 focus:ring-blue-300" 
                                    type="checkbox" 
                                    value='' 
                                    id="remember"/>
                            </div>
                            <label htmlFor="remember" className="ml-2 text-sm font-medium text-white">
                                I agree with the <a href="#" className="text-blue-600 hover:underline dark:text-blue-500">terms and conditions</a>.
                            </label>
                            <Link href="./" className="mr-5 mt-5 font-medium text-white text-right hover:underline decoration-solid">
                                Return to login &lt;--
                            </Link>
                            {error && <div>{error}</div>}
                        </div>
                    </div>
                    <button type="submit" className="ml-5 mb-5 text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm w-full sm:w-auto px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Submit</button>
                </form>
            </div>
        </main>
    </>
  )
}

推荐答案

您的NextResponse中似乎有一些格式错误的JSON 在返回NextResponse之前,我会通过控制台登录JSON.stringify(responseThatIWantToSend)来判断它们是否有效. 另外,为了清楚起见,我将只使用具有try...catch语法的async...await.

// specific name for the function
export async function createUser(req: NextRequest) {
  try {
    await dbConnect()
    const res = await req.json()
    const hashedPassword = await bcrypt.hash(res.passwd, 10)
    const user = new User({
      firstname: res.firstname,
      lastname: res.lastname,
      company: res.company,
      phone: res.phone,
      email: res.email,
      password: hashedPassword,
    })

    await user.save();
    // Try first sending back simple reponses to see if it works
    // if it does, add status and user props to your response
    return NextResponse.json({
      message: 'User saved'
    })
  } catch (error) {
    // degug error
    console.log('error', error);
    return NextResponse.json(error, {
      status: 500
    })
  }
}

Javascript相关问答推荐

如何在非独立组件中使用独立组件?

如何在使用fast-xml-parser构建ML时包括属性值?

我在这个黑暗模式按钮上做错了什么?

MongoDB中的引用

Phaser 3 console. log()特定游戏角色的瓷砖属性

我应该绑定不影响状态的函数吗?'

google docs boldText直到按行执行应用脚本错误

成功完成Reducers后不更新状态

如何用拉威尔惯性Vue依赖下拉?

无法访问Vue 3深度监视器中对象数组的特定对象值'

Regex结果包含额外的match/group,只带一个返回

我的角模板订阅后不刷新'

在使用HighChats时如何避免Datatables重新初始化错误?

编剧如何获得一个div内的所有链接,然后判断每个链接是否都会得到200?

如何在文本字段中输入变量?

查询参数未在我的Next.js应用路由接口中定义

在css中放置所需 colored颜色 以填充图像的透明区域

使用Ace编辑器对子组件实例的native-element 进行Angular 获取时面临的问题

未捕获的运行时错误:调度程序为空

如果对象中的字段等于某个值,则从数组列表中删除对象