【问题标题】:having trouble in passing req data in post fumction through html form in node js通过节点js中的html表单在post函数中传递req数据时遇到问题
【发布时间】: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


【解决方案1】:

查看 body-parser README 部分的注释(附上截图供参考)。由于其复杂性,BodyParser 不支持多部分样式。相反,列出了一些要使用的 nm 模块。

我建议MULTER 或MILTIPARTY

这里是工作代码的参考。我已将接收到的有效负载作为 JSON 响应发送。您可以按照自己的意愿继续处理。

router.post('/ola', (req, res) => {
  var form = new multiparty.Form();
  form.parse(req, function(err, fields, files) {
    res.json({ fields: fields, files: files });
  });
  
})

【讨论】:

  • 我已经在我的代码中使用了这个。但它仍然显示该错误
  • @codemarvel 的上述评论是针对较早的解决方案。我已经用经过测试的解决方案更新了答案。看看吧。
猜你喜欢
  • 1970-01-01
  • 2021-05-23
  • 2014-12-26
  • 2020-03-09
  • 2020-08-14
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 2021-03-24
相关资源
最近更新 更多