【问题标题】:res.send not working for object?res.send 对对象不起作用?
【发布时间】:2016-03-19 22:49:15
【问题描述】:

代码如下,htis是使用express框架的node.js:


var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Expressxx' });
});

router.post('/', function(req, res, next) {

  var body = '';

  req.on('data', function(chunk) {
     body += chunk;
     });

  req.on('end', function() {
     console.log(body);
     });

  /* res.send('Got the Post'); */

  res.set('Content-Type', 'text/plain');
  res.send('this is the body' + body);
  res.end();

});

module.exports = router;

当我执行 console.log(body);我看到了预期的数据,但在客户端我看到的只是“这是身体”。似乎 res.send 无法读取正文 obj?

谢谢....

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    您上面的代码在触发data 事件之前发送响应,因此永远不会构建body。在end 事件处理程序中移动res.send 和相关调用应该会得到你想要的。

    【讨论】:

      【解决方案2】:

      经过更多测试,如果 res.send 是 Json obj,似乎 res.send 将发送一个 obj……在我的情况下,它只是正文 obj 中的纯文本。

      当我在这里读到这种方法时...... http://expressjs.com/en/api.html#res.send

      它说: body参数可以是Buffer对象、String、对象或Array

      没说必须是json obj???

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-03-30
        • 2023-03-29
        • 2023-03-13
        • 1970-01-01
        • 2018-05-03
        • 2017-05-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多