简体   繁体   中英

I can't get my Ajax jquery Post Request to send object correctly?

I'm trying to do a POST Request, but my Server keeps telling me I'm not sending the values correctly?

This checks for required fields and returns an error if it's missing, it keeps saying that name is missing from the request body.

This is on my router:

router.post('/', jsonParser, (req, res) => {
  const requiredFields = ['name', 'size', 'prices'];
  for (let i = 0; i < requiredFields.length; i++) {
    const field = requiredFields[i];
    if (!(field in req.body)) {
      const message = `Missing \`${field}\` in request body`;
      console.error(message); // responds missing `name` in request body
      return res.status(400).send(message);
    }
  }

  StoredProduct.create({
    name: req.body.name,
    size: req.body.size,
    prices: req.body.prices
  }).then(item => {
    res.status(201).json(item);
  }).catch(err => {
    console.log(err);
    res.status(500).json({
      error: err
    });
  });

});

And then this is my AJAX Request:

$('#addItemButton').on('click', function() {
  console.log($addProductName.val()); //works correctly
  console.log($addProductUnit.val()); //works correctly 
  console.log($addPrice1.val()); //works correctly
  console.log($addPrice2.val()); //works correctly
  console.log($addPrice3.val()); //works correctly
  var newProd = {
    name: $addProductName.val(),
    size: $addProductUnit.val(),
    prices: [{
        price: $addPrice1.val()
      },
      {
        price: $addPrice2.val()
      },
      {
        price: $addPrice3.val()
      }
    ]
  };

  $.ajax({
    type: 'POST',
    url: '/storedproducts',
    data: newProd,
    success: function(newProd) {
      console.log(`${newProd} created`);
    },
    error: function() {
      alert(`didn't work item: ${newProd}`); // responds didn't work item: [object Object]
    }
  });

});

Server response is 400 (Bad Request) and in my server logs it shows "Missing name in request body

I am using body-parser, and I needed to add the following to my main server.js file to send the data over correctly.

app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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