【发布时间】:2020-11-05 06:40:19
【问题描述】:
我是 nodejs 的新手。通过 html 表单发布数据时面临问题.... 在我的 server.js 中,我添加了这个帖子功能请求
app.get('/',(req,res)=>{
res.end(`
<!doctype html>
<html>
<body>
<form action="/product" method="post" role="form" enctype="multipart/form-data">
<input type="text" id="title" name="title" placeholder="title">
<input type="number" name="price" placeholder="price">
<input type="text" name="description" placeholder="description">
<input type="text" name="category" placeholder="category" >
<input type="file" name="product" >
<button>Save</button>
</form>
</body>
</html>
`);
})
product.js 中的发布函数声明
const productRouter = express.Router();
productRouter.use(bodyParser.json());
productRouter.route('/')
.get((req,res,next)=>{
Product.find({})
.then((products)=>{
res.statusCode=200;
res.setHeader('Content-Type','application/json');
res.json(products);
},(err)=>next(err))
.catch((err) => next (err));
})
.post((req,res,next)=>{
console.log(req.body);
var Prod= new Product({
title:req.body.title,
price:req.body.price ,
description: req.body.description,
category:req.body.category,
img: req.body.img
});
Prod.save()
.then((product)=>{
console.log('product added ',product );
res.statusCode=200;
res.setHeader('Content-Type','application/json');
res.json(product);
},(err)=> next(err))
.catch((err) => next(err));
})
当我使用 POSTMAN 时,发布请求工作正常,但是当我尝试使用 html 表单时,我面临以下错误:
ValidationError:产品验证失败:标题:路径title是必需的,价格:路径price是必需的,描述:路径description是必需的,类别:路径category是必需的,img :路径img 是必需的。
在 model.Document.invalidate (C:\Users\mayank\Desktop\cata\node_modules\mongoose\lib\document.js:2598:32)
【问题讨论】:
-
什么是 console.log(req.body) 打印?
-
@SatyaKalluri 它只是给了一个空对象.... {}
-
在答案部分发布了一个潜在的解决方案。告诉我,进展如何。
-
好的,明白了。我的也不好。 body-parser 不能直接用于多部分内容。我已经更新了完成工作的解决方案。检查并告诉我。干杯
标签: javascript html node.js