app.use(restify.bodyParser())无效,因为req对象为空

时间:2015-02-21 20:28:13

标签: javascript node.js restify body-parser

我正在使用restify,对于HTTP POST调用,请求对象始终为空。谁能告诉我可能的原因。

此致

1 个答案:

答案 0 :(得分:0)

您收到"Invalid JSON: Unexpected token u"因为您尝试将undefined解析为JSON。要阻止请求正文undefined执行以下操作:

  1. 检查您的代码应如下所示:

    var restify = require('restify');
    var server = restify.createServer();
    
    // This line MUST appear before any route declaration
    server.use(restify.bodyParser());
    
    server.post('/customer/:id', function (req, resp, next) {
      console.log("The request body is " + req.body);
      response.send("post received. Thanks!");
      return next();
    });
    
  2. 检查您的内容类型是否有效。例如

    curl -H 'Content-Type: application/json' -X POST ...