通过ajax和jQuery将JSON中的表单数据提交给Node.js网络服务器

时间:2014-11-26 00:46:44

标签: jquery ajax json node.js post

这一定是一个简单的问题而且我没有看到错误在哪里,所以在阅读并尝试了很多事情而没有进展之后,我会投降寻求帮助!

HTML

...
<form id="FichaCadastral" method="POST">
  <input id="CPF" type="text">
  ...
  <input type="submit" value="Submit">
</form>
...

的JavaScript

$(function () {
  $('#FichaCadastral').on('submit', function (e) {
    var opa = {id: 3}; //Simple test data

    $.ajax({
      url: $(location).attr('pathname'), //I just want to know what webpage posted data
      method: 'POST',
      type: 'POST',
      data: JSON.stringify(opa),
      processData: false,
      dataType: 'json', 
      contentType: 'application/json; charset=utf-8',
    }); //No success/done/fail callbacks for now, I'm focusing on this problem first

    e.preventDefault();
  });
}

Node.js的

...
server = http.createServer();
server.on('request', function (request, response) {
  if (request.method === 'POST') console.log(request.body); //shows 'undefined' in node-dev console
});

我不知道上面的代码是错误,因为我在所有代码中都是新的。

2 个答案:

答案 0 :(得分:1)

默认情况下,节点不处理实体主体(POST数据)。相反,原始字节作为data事件发出。您负责解析请求流。

我建议您在服务器上使用Expressbody-parser中间件。


此外,

url: location.pathname

location是一个常规的JavaScript对象。没有必要将它包装在jQuery中。

答案 1 :(得分:1)

只是为了在不使用Express或正文解析器的情况下给出完整的答案,这里是我正在使用的新代码及其工作原理:

<强> Node.js的

...
server = http.createServer();
server.on('request', function (request, response) {
  ...
  var data = '';
  request.on('data', function (chunk) {
    data += chunk;
  });
  request.on('end', function () {
    if (data) {  //data shows '{"id":3}' in node-dev console
      if (request.method === 'POST') response = sPOSTResponse(request, data, response);
      //calls a method for controling POST requests with data captured
    };
  });
});