简体   繁体   English

我无法使用 multer 检索 req.body 数据

[英]I can't retrieve req.body data with multer

I can't retrieve the data from req.body using multer.我无法使用 multer 从 req.body 检索数据。 It responds with [Object: null prototype] {} , if I stringify it as JSON I ofc get {} My goal is to receive input number in order to add X amount of product to the cart, but I can't seem to get the number.它响应 [Object: null prototype] {} ,如果我将其字符串化为 JSON I ofc get {} 我的目标是接收输入编号以便将 X 数量的产品添加到购物车,但我似乎无法得到号码。

{{# each products }}

  <div class="row">
    {{# each this }} 
    <div class="col-sm-6 col-md-4">
    <form action = "/add-to-cart/{{this._id}}" method="post" enctype="multipart/form-data">
    
      <div class="img-thumbnail" alt="text-center">
   <div class="thumbnail">
      <img src="{{this.imagePath}}" class="img-fluid" alt="Responsive image">
      <div class="caption">
        <h3>{{this.title}}</h3>
        <p class="description">{{this.description}}</p>
        <div class="clearfix">
           <input  type="text" name="Quantity" placeholder="vnt" form="insert-id-of-form" class="float-left">
            <div class="price float-left">{{this.price}}</div>
        <input type="submit" class="fadeIn fourth" value="Užsakyti">
        </div>
      </div>
    </div>
      </div>
  </div>
    </form>
    {{/each}}
   
</div>
  {{/each}}

This is my code in.js这是我在 .js 中的代码

router.post('/add-to-cart/:id',upload.single("Quantity"), function(req, res, next) {
    var productId = req.params.id;
    var cart = new Cart(req.session.cart ? req.session.cart : {});
    Product.findById(productId, function(err, product) {
      var boxSize = req.session.boxSize;
      const itemQty = req.body;
      console.log(itemQty);
       if (err) {
           return res.redirect('/products');
       }
       else if (cart.boxSizeQty < boxSize && itemQty == null){
        cart.add(product, product.id);
        req.session.cart = cart;
        res.redirect('/products');
        console.log("item qty null")
       }
       else if (cart.boxSizeQty >= boxSize && itemQty > boxSize){
         res.redirect('/products');
         req.flash('error','Dėžutė pilna');
         console.log("more items than size")
       }
       else if (cart.boxSizeQty < boxSize && itemQty > 0){
         console.log("item quantity is more than 0")
         for (var i = 0; i <= itemQty; i++){
          cart.add(product, product.id);
         }
         req.session.cart = cart;
         res.redirect('/products');
       }
       
    });
});

This is part of the app.sj这是 app.sj 的一部分

var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
var app = express();
var bodyParser = require('body-parser')
var multer = require('multer');
var forms = multer();

mongoose.connect('mongodb://localhost:27017/shopping', {useNewUrlParser: true, useUnifiedTopology: true});
require('./config/passport');
// view engine setup
app.use(bodyParser.json());
app.use(forms.array());
app.use(bodyParser.urlencoded({   extended: true }));
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname: '.hbs'}));
app.set('view engine', '.hbs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());

I've tried this with multer, formidable, bodyparser but it doesn't seem to parse the input number.我已经用 multer、强大的 bodyparser 尝试过这个,但它似乎没有解析输入数字。 Very much stuck on this.非常坚持这一点。 Any help would be appreciated.任何帮助,将不胜感激。

Kind regards,亲切的问候,

Just posting the answer here, if anyone will get in to a similar issue.如果有人会遇到类似的问题,只需在此处发布答案。

Apparently the problem was that for data wasn't being passed though nodejs part was working fine.显然,问题是尽管 nodejs 部分工作正常,但没有传递数据。 It's my mistake for not going to developer options on browser and checking form data which was empty.我没有在浏览器上访问开发人员选项并检查空的表单数据是我的错误。

Once html part is in one div一旦 html 部分在一个 div 中

{{# each products }}
  <div class="row form-group">
    {{# each this }} 
    <form action = "/add-to-cart/{{this._id}}" method="post" enctype="multipart/form-data">
    <div class="form-group">
      <img src="{{this.imagePath}}" class="img-fluid" alt="Responsive image">
        <h3>{{this.title}}</h3>
        <p class="description">{{this.description}}</p>
           <input  type="number" name="Quantity" placeholder="vnt" class="float-left">
        <input type="submit" class="fadeIn fourth" value="Užsakyti">
  </div>
    </form>
    {{/each}}
   
</div>
  {{/each}}

The data is being properly passed from this form.数据正从此表单正确传递。

Then we need to stringify it to JSON like so:然后我们需要像这样将其字符串化为 JSON:

 var itemQty = JSON.parse(JSON.stringify(req.body.Quantity));

And parse it as int like so:并将其解析为 int ,如下所示:

 parseInt(itemQty);

All is left is to fix the view.剩下的就是修复视图。

Thanks to anyone who bothered to read.感谢所有愿意阅读的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM