【问题标题】:Submit/POST form data in JSON via ajax and jQuery to a Node.js webserver通过 ajax 和 jQuery 以 JSON 格式提交/POST 表单数据到 Node.js 网络服务器
【发布时间】:2015-01-24 05:04:08
【问题描述】:

这一定是一个简单的问题,我看不出错误在哪里,所以在阅读并尝试了很多东西但没有任何进展之后,我投降寻求帮助!

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
});

我不知道上面的哪个代码是错误的,因为我是所有这些代码的新手。

【问题讨论】:

  • 你在哪里引用 JavaScript?未包含的 HTML 的某些部分?
  • 另外,你可能想看看stackoverflow.com/a/12007627/3412775
  • @Tomty 是的,我在头部 jQuery 和特定于页面的 js 中引用。感谢您的链接!它对我帮助很大,有很多类似的问题,但没有一个像那样有完整的答案

标签: jquery ajax json node.js post


【解决方案1】:

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

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


还有,

url: location.pathname

location 是一个常规的 JavaScript 对象。无需将其包装在 jQuery 中。

【讨论】:

  • 谢谢。我没有使用 Express 或 body-parser 来了解一切是如何工作的,但可以肯定的是,这会容易得多。关于jQuery,不记得我为什么这样做了,任何人都会这样做。
【解决方案2】:

只是为了在不使用 Express 或 body-parser 的情况下给出完整的答案,这是我正在使用的新代码及其工作:

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
    };
  });
});

【讨论】:

    猜你喜欢
    • 2017-01-21
    • 2017-02-18
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多