嘗試使用該POST
方法postman
注冊用戶后出現錯誤。我Schema
為register
路線創建了一個簡單的。
錯誤:
Error in register: Error: User validation failed: password: Cast to string failed for value "Promise { <pending> }" (type Promise) at path "password"
at ValidationError.inspect (/Users/*****/authSystem/node_modules/mongoose/lib/error/validation.js:48:26)
at formatValue (node:internal/util/inspect:782:19)
at inspect (node:internal/util/inspect:347:10)
at formatWithOptionsInternal (node:internal/util/inspect:2167:40)
at formatWithOptions (node:internal/util/inspect:2029:10)
at console.value (node:internal/console/constructor:324:14)
at console.log (node:internal/console/constructor:360:61)
at /Users/harshmishra/Desktop/BackendApp/authSystem/app.js:46:17
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errors: {
password: CastError: Cast to string failed for value "Promise { <pending> }" (type Promise) at path "password"
at SchemaString.cast (/Users/*****/authSystem/node_modules/mongoose/lib/schema/string.js:600:11)
at SchemaString.SchemaType.applySetters (/Users/*****/authSystem/node_modules/mongoose/lib/schematype.js:1189:12)
at model.$set (/Users/***/authSystem/node_modules/mongoose/lib/document.js:1409:20)
at model.$set (/Users/*****/authSystem/node_modules/mongoose/lib/document.js:1137:16)
at model.Document (/Users/****/authSystem/node_modules/mongoose/lib/document.js:162:12)
at model.Model (/Users/****/authSystem/node_modules/mongoose/lib/model.js:115:12)
at new model (/Users/*****/authSystem/node_modules/mongoose/lib/model.js:4825:15)
at /Users*****/authSystem/node_modules/mongoose/lib/model.js:3132:22
at /Users/*****/authSystem/node_modules/mongoose/lib/model.js:3168:7
at Array.forEach (<anonymous>) {
stringValue: '"Promise { <pending> }"',
messageFormat: undefined,
kind: 'string',
value: [Promise],
path: 'password',
reason: null,
valueType: 'Promise'
}
},
_message: 'User validation failed'
}
架構:
const userSchema = new mongoose.Schema(
{
firstName: {
type: String,
default: null,
},
lastName: {
type: String,
default: null,
},
email: {
type: String,
unique: true,
},
password: {
type: String,
},
token: {
type: String,
},
},
);
module.exports = mongoose.model('User', userSchema)
/登記:
app.post("/register", async(req, res) => {
try {
const { firstName, lastName, email, password } = req.body;
if (!(firstName && lastName && email && password)) {
return res.status(400).send("All fields are required");
}
const existingUser =User.findOne({ email });
if (existingUser) {
return res.status(401).send("User already exist");
}
const myEncrpytedPass = await bcryptjs.hash(password, 10);
const user = await User.create({
firstName,
lastName,
email: email.toLowerCase(),
password: myEncrpytedPass,
});
const token = await jwt.sign(
{
user_id: user._id,
email,
},
process.env.SECRET_KEY,
{
expiresIn: "4h",
}
);
user.token = token;
return res.status(201).json(user);
} catch (error) {
console.log("Error in register:",error)
}
})
我無法弄清楚我在這里做錯了什么?正如我遵循貓鼬的檔案,但我仍然收到錯誤。
我應該在這里做些什么改變?
uj5u.com熱心網友回復:
您需要更改兩件事:
第一的
嘗試await
在bcryptjs.hash()
. 看起來該函式回傳了一個 Promise。
const myEncrpytedPass = await bcryptjs.hash(password, 10);
第二
在return
每個res.send
.
例如,如果用戶存在,您將發送 this res.send(401).send("User already exist")
,但由于您沒有添加return
,功能將繼續,并會到達下一個res.status(201).json(user)
回應。這將引發錯誤,Cannot set headers after they are sent to the client
因為您已經將回應發送給用戶。
uj5u.com熱心網友回復:
app.post("/register", async(req, res) => {
try {
const { firstName, lastName, email, password } = req.body;
if (!(firstName && lastName && email && password)) {
res.status(400).send("All fields are required");
}
const existingUser = await User.findOne({ email });
if (existingUser) {
res.send(401).send("User already exist");
}
const myEncrpytedPass = await bcryptjs.hash(password, 10);
const user = await User.create({
firstName,
lastName,
email: email.toLowerCase(),
password: myEncrpytedPass,
});
const token = await jwt.sign(
{
user_id: user._id,
email,
},
process.env.SECRET_KEY,
{
expiresIn: "4h",
}
);
user.token = token;
res.status(201).json(user);
} catch (error) {
console.log("Error in register:",error)
}
})
您需要等待 jwt 簽名和 bcrypt
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/489430.html
上一篇:spark.read.json()如何使用動態年份引數讀取檔案
下一篇:查詢陣列中每個元素的貓鼬