[英]I am trying to hash admin password to save into database using bcrypt in nextjs but receiving error
所以如果我不导入 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();
};
发生该错误是因为在您应用程序的客户端某处您正在使用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
签约,然后运行
等待 user.save()
所以在保存“用户”之前,原始密码将自动散列,散列密码将保存到数据库中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.