【问题标题】:Getting JSON-objects with Node.js WITHOUT stream在没有流的情况下使用 Node.js 获取 JSON 对象
【发布时间】:2019-09-16 08:33:58
【问题描述】:

我正在尝试使用 vanilla javascript 在客户端(网络浏览器)和服务器(Node.js)之间进行 JSON 对象交换。我在客户端和 POST 方法中使用 httpRequest。在服务器上,我想从该 POST 请求中获取 JSON 数据,但我觉得流和块太复杂了。有没有办法像一个简单的对象一样获取数据?它存在吗?

客户端请求(看起来不错):

button.onclick = function serverCommunication() {   
  var serverInteraction = new XMLHttpRequest('POST', '/chooochooo', true);
  serverInteraction.open("POST", '/logInAttempt', true);
  serverInteraction.setRequestHeader('Content-Type', 'application/json'); 
  serverInteraction.send(JSON.stringify(myObject));// JSON-data has been sent, hoooraaaa! 
};

【问题讨论】:

    标签: javascript node.js json post xmlhttprequest


    【解决方案1】:

    你可以试试这个

    if(req.method === 'POST')
       let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
    console.log(body);
    

    但这有其局限性,我建议使用 express 来处理请求。

    【讨论】:

      猜你喜欢
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 2014-10-07
      相关资源
      最近更新 更多