简体   繁体   English

我无法获取我的Ajax jQuery发布请求以正确发送对象?

[英]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? 我正在尝试执行POST请求,但是我的服务器不断告诉我我没有正确发送值?

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: 然后这是我的AJAX请求:

$('#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 服务器响应为400(错误请求),并且在我的服务器日志中显示"Missing in request body "Missing名称

I am using body-parser, and I needed to add the following to my main server.js file to send the data over correctly. 我正在使用body-parser,我需要将以下内容添加到我的主server.js文件中,以正确发送数据。

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

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

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