【问题标题】:How to handle sent data to server in express?如何处理以快递方式发送到服务器的数据?
【发布时间】:2018-12-22 09:10:27
【问题描述】:

我将这个帖子请求从我的index.js 发送到我的app.js(在点击事件上):

var data = {
   name: "Sarah",
   age: "21"
};
var xhr = new XMLHttpRequest();
    xhr.open("POST", "/", true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({
        data: data
    }));

然后在我的app.js,我有这个:

app.post('/', function(req, res) {

    if(req.xhr) {
        console.log(req.body.name); 
    }

 });

但是过了一会儿,控制台什么也没有记录?我也安装了body-parser。有什么遗漏吗?

一段时间后,我也在控制台中收到此错误消息:

POST http://localhost:8080/ 0 ()

【问题讨论】:

  • 您没有发送回复? res.end()。或发送状态码。
  • 我猜应该是req.body.data.name。还有res.send()也是需要的
  • 你可以通过sn -p console.log(req.body);查看req.body对象,然后你可以看到body对象没有任何名为name的字段,body只有一个字段 - data。另一种方式,您在客户端进行更改 xhr.send(JSON.stringify(data);
  • 添加 res.send() 有效。谢谢@dhilt

标签: javascript node.js express post xmlhttprequest


【解决方案1】:

不需要添加if条件 试试这个

app.post('/', function(req, res) { console.log(req.body.code);  });

【讨论】:

    【解决方案2】:

    所以从 cmets 开始,我在我的 app.js 中进行了这个更改:

    app.post('/', function(req, res) {
    
        res.send(req.body.data);
    
    });
    

    然后在我的index.js

    var xhr = new XMLHttpRequest();
        xhr.open("POST", "/", true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(JSON.stringify({
            data: data
        }));
    
        xhr.onreadystatechange = function(){
          if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
              console.log(xhr.responseText);
            } else {
              alert('There was a problem with the request.');
            }
          }
        }
    

    基本上,我最初错过了res.send()。发送该信息后,我就可以在index.js 上回复console.log

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-27
      • 2019-06-06
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 1970-01-01
      • 2019-12-23
      相关资源
      最近更新 更多