![](/img/trans.png)
[英]Serverless API offline testing recieving validation error when sending post req data to MongoDB via postman
[英]error in sending data to mongodb from my own api
實際上,我正在開發一個顫振應用程序,它將數據發送到我自己在節點 js 中創建的 API,然后數據進入 MongoDB 集群,當我測試 API 使其正常工作並且數據進入 MongoDB 但當我嘗試發送時來自我的顫振應用程序的數據,因此它給出了以下錯誤:
(node:4856) UnhandledPromiseRejectionWarning: ValidationError: User validation failed: name: Path `name` is required., email: Path `email` is required., password: Path `password` is required.
我認為所需的數據沒有接收到 MongoDB,所以我創建了一個簡單的 javascript 應用程序,將該數據發送到 API,但我收到了同樣的錯誤,我認為這是我的 API 的錯誤,但它仍然可以當我從郵遞員或迅雷客戶端發送數據時。 這是我創建的 API 代碼:
const DB = "mydburl"
app.use(express.json());
app.post('/api/signup', async (req, res) => {
const {name, email, password} = req.body;
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ msg: "User with same email already already exists" })
}
const hashedPassword = await bcryptjs.hash(password, 8);
let user = new User({
email,
password : hashePassword,
name,
});
res.json(user)
user = await user.save();
console.log(user);
});
mongoose.connect(DB).then(() => {
console.log("connection succesful")
})
.catch((e) => {
console.log(e);
})
app.listen(PORT, "0.0.0.0", () => {
console.log(`connected at port ${PORT}`)
});
app.post('/api/signup', async (req, res) => {
const {name, email, password} = req.body;
console.log(`name=${name} , email = ${email} , password=${password}`);
const existingUser = await User.findOne({ email });
if (existingUser) {
return res.status(400).json({ msg: "User with same email already already exists" })
}
const hashedPassword = bcryptjs.hashSync(password, 8);
let user = new User({
email:email,
password : hashePassword,
name:name
});
user.save().then((userSaved)=>{
return res.status(200).json(user);
}).catch((e)=>{
return res.status(500).json({status:"error",error:e})
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.