app.use(restify.bodyParser())无法工作,因为req对象为空

app.use(restify.bodyParser()) not working as req object is empty

本文关键字:req 因为 对象 restify use bodyParser app 工作      更新时间:2024-03-09

我使用restify,对于HTTPPOST调用,请求对象总是空的。谁能告诉我可能的原因吗。

问候

您收到"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 ...