简体   繁体   中英

How to pass ajax post data to nodejs server?

So I'm making an API call and one of the objects within that call is a unique ID. I'm trying to pass that ID object back server side using Ajax. It's not working. What am I doing wrong?

Here is my client side code, first I loop through a javascript object:

<% apiResultsdata['items'].forEach(function(items) { %>

    <% let ID = items['id'] %>
    <% let volumeInfo = items['volumeInfo'] %>
    <% let author = volumeInfo['authors'] %>
    <% let title = volumeInfo['title'] %>
    <% let image = null %>
    <% if(!(volumeInfo['imageLinks'] === undefined)) { %>
      <% image = volumeInfo['imageLinks']['smallThumbnail'] %>
 <% } %>

ID is what I need to pass back to nodejs after a link is clicked:

<div class="col">
                <div class="card-block px-2">
                  <a  href="/bookDetails"><h5 class="card-title"><%= title %></h5></a>


                  <script type="text/javascript">
                      $('a').click(function() {
                        $.ajax({
                          type: 'post',
                          data: {'ID':'<%= ID %>'},
                          url: 'localhost:3000/bookDetails',
                          success: function(data){
                            console.log('success');
                          }
                        });
                      });
                  </script>

In my data filed, I'm passing ID as a ejs object because that's the templating language I'm using. Not sure if that's right.

Here is the post route on the server:

router.post('/bookDetails', (req, res) => {
  let ID = req.query.ID;
  console.log('ID: ' + ID);
});

You need to set contentType and JSON.stringify the object before passing to the data field. ( check this thread )

$.ajax({
    type: 'post',
    contentType: "application/json; charset=UTF-8",
    data: JSON.stringify({ ID: '<%= ID %>' }),
    url: 'localhost:3000/bookDetails',
    success: function(data) {
        console.log('success');
    }
});

And it's always a good idea to use a json-parser middleware on the server side

const bodyParser = require('body-parser');
app.use(bodyParser.json());

Then you can get the request body that contains the ID parameter as follows

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

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