我正在尝试使用 nextjs 中的 bcrypt 对管理员密码进行哈希处理以保存到数据库中,但收到错误

问题描述 投票:0回答:2

所以如果我不导入 bcrypt 一切都很好,但是一旦我这样做,我会在终端中收到以下错误。我已经搜索了很多,但没有运气,此时我不知道该怎么做。任何帮助将不胜感激。

error - ./node_modules/@mapbox/node-pre-gyp/lib/clean.js:8:0
Module not found: Can't resolve 'fs'

Import trace for requested module:
./node_modules/@mapbox/node-pre-gyp/lib/ sync ^\.\/.*$
./node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js
./node_modules/bcrypt/bcrypt.js
./pages/adminlogin.js

https://nextjs.org/docs/messages/module-not-found

这是我的 adminlogin.js 文件

import bcrypt from "bcrypt";
export default function AdminLogin() {
  const saltRounds = 10;
  const createAdminData = async (e) => {
    const usernameInfo = e.target.username.value;
    console.log(usernameInfo);
    const passwordInfo = e.target.password.value;
    const salt = bcrypt.genSalt(saltRounds);
    const hashedPassword = bcrypt.hash(passwordInfo, salt);
    const res = await fetch("api/database/addadmindata", {
      method: "POST",
      headers: {
        "Content-type": "application/json",
      },
      body: JSON.stringify({
        username: usernameInfo,
        password: hashedPassword,
      }),
    });
    const result = await res.json();
    router.reload();
  };

 
node.js mongoose next.js bcrypt
2个回答
3
投票

发生该错误是因为在应用程序的客户端某处您正在使用

fs
模块。您只能在服务器端使用
fs
模块,无论是
getserverSideProps
或 apis 目录。

当您导入“fs”并在服务器端使用它时,next.js 会看到您在服务器端使用它,因此它不会将该导入添加到客户端包中

可能 @mapbox 不是客户端库,但您在客户端使用它

您可能有 mongoose userSchema。在该架构文件中:

// hashing password before saving user
// for findAndUpdate(), pre save hook is not triggered
userSchema.pre("save", async function (next) {
  // if password did not get changed, next()
  if (!this.isModified("password")) {
    next();
  }
  this.password = await bcrypt.hash(this.password, 10);
});

现在您不需要在服务器上进行哈希处理。您从

req.body
中提取数据,使用原始密码收缩
user
,然后运行

等待用户.save()

因此在保存“用户”之前,原始密码将自动进行哈希处理,并将哈希密码保存到数据库中


0
投票

您可以使用“bcryptjs”代替“bcrypt”,它在 nextjs 13 的客户端工作正常

© www.soinside.com 2019 - 2024. All rights reserved.