简体   繁体   English

如何将Ajax发布数据传递到Node.js服务器?

[英]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. 因此,我正在进行API调用,并且该调用中的对象之一是唯一ID。 I'm trying to pass that ID object back server side using Ajax. 我正在尝试使用Ajax将ID对象传递回服务器端。 It's not working. 没用 What am I doing wrong? 我究竟做错了什么?

Here is my client side code, first I loop through a javascript object: 这是我的客户端代码,首先我遍历一个javascript对象:

<% 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: 单击链接后,我需要将ID传递回nodejs:

<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. 在我提交的数据中,我将ID作为ejs对象传递,因为这是我使用的模板语言。 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. 您需要先设置contentTypeJSON.stringify对象,然后JSON.stringify数据字段。 ( 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 在服务器端使用json-parser中间件总是一个好主意

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

Then you can get the request body that contains the ID parameter as follows 然后,您可以获取包含ID参数的请求正文,如下所示

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

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

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