简体   繁体   中英

Why my Ajax object comes back as undefined?

I'm trying to make an Ajax request, but my object keeps coming back as undefined.

Here's my client side code:

<a class="clicklink" href="/bookDetails"><h5 class="card-title"><%= title %></h5></a>

<script type="text/javascript">
$(document).ready(function(){
  $(".card-title").click(function(){
    $.ajax({
      type: 'post',
      contentType: "application/json; harset=UTF-8",
      data: JSON.stringify({ID:'<%= ID %>'}),
      url: 'http://localhost:3000/bookDetails',
      success: function(data){
        console.log('success');
      }
    });
  });
});
</script>

Here is my post request code:

router.post('/bookDetails', (req, res) => {
  console.log(req.body.ID);
});

BTW, I'm putting my <h5> tag inside a link so it's clickable. I don't maybe that's the problem but I don't think so. But this is the error I get back:

Cannot read property 'ID' of undefined

Any ideas? Thanks.

If you're using Express, make sure you have the body-parser middleware enabled.

Related Post: Express.js req.body undefined

The error message tells you that the property cannot be read because the parent is undefined. One common cause of this is that the response from the ajax call is a string rather than an object. Have you checked the return type?

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