【问题标题】:Express.js post request gives undefinedExpress.js 发布请求给出未定义的
【发布时间】:2013-12-06 22:07:49
【问题描述】:

我以前用 express.js 解析 post 请求正文,但现在当我尝试登录 req.body.gsm 时它开始给出未定义。 {"gsm":"10"}这是我的帖子数据,我向休息客户端提出请求。

   app.configure(function(){
      app.use(express.bodyParser());
      app.use(app.router);
      app.use(express.static(__dirname + '/public'));
    });

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

  var gsm = req.body.gsm; //gsm is undefined when i log

  var body = req.body;  //this is the log of body { '{\n"gsm":"10"\n}': '' }

  });

【问题讨论】:

  • 看来问题不在nodejs部分,而在客户端代码。 IE。您提交数据的地方。能否请您发布该脚本。
  • 我正在使用 cocoaRestClient,这是我发布的数据:{"gsm":"10"}
  • 我想看看发送数据的实际代码。可能您将数据作为字符串发送。因此,如果您之前使用 JSON.stringify 将数据传递给 cocoaRestClient,请将其删除。

标签: node.js express rest-client


【解决方案1】:

看起来您将正文作为字符串而不是 JSON 对象接收。只有设置了Content-type: application/json 标头,Express 才会将正文解析为完整的 JSON 对象,参见connect's json middleware 的源代码。

只需发送带有Content-type: application/json 标头的相同请求即可。

用于测试的示例 curl 脚本:

$ curl -XPOST -H "Content-type: application/json" -d '{"gsm":"10"}' "http://localhost/gsm"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 2020-01-08
    • 1970-01-01
    • 2013-12-24
    • 2021-06-07
    • 2021-03-01
    • 2021-09-10
    相关资源
    最近更新 更多