[英]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.