简体   繁体   中英

How to recieve data from a ajax post request

I am new to ajax/jquery and I am trying to send a variable with a post request with ajax/jquery to the server and then console log it.

But for some reason when I console log it again from the server it stays undefined, so how do I properly send it off and retrieve it?

Code inventory.js:

$('form').on('submit', function() {

  var temp = {test: 0}

  $.ajax({
    type: 'POST',
    url: '/inventoryactionbtn',
    data: temp,
    success: function(data) {
      //do something with the data via front-end framework
    }
  });

  return false;
})

Index.js:

router.post('/inventoryactionbtn',  ensureAuthenticated, function(req, res) {
  var testing= req.body
  console.log(testing)
})

There are three problems:

You aren't running your client-side JS

 $('inventoryactionbtn')

Will match <inventoryactionbtn> elements which aren't allowed in HTML. Probably you intended that to be an ID or class selector so you need the appropriate prefix.

submit events only fire on <form> elements so since you are targetting something with btn in the name, you are probably targetting the wrong element anyway.

You need a body parsing middleware

See the API reference :

Contains key-value pairs of data submitted in the request body. By default, it is undefined , and is populated when you use body-parsing middleware such as express.json() or express.urlencoded() .

There's no sign of any body-parsing middleware in the code you've provided. You need to use some which matches the format of the data you are POSTing.

You need to get the URL right

/http://localhost:5000/inventory , even if you remove the / at the front, doesn't match (wherever you have mounted the router +) /inventoryactionbtn

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