【问题标题】:Request body in express is undefined?快递中的请求正文未定义?
【发布时间】:2016-06-01 10:19:08
【问题描述】:

我正在使用 Alamofire(在 iOS 中)发出一个简单的 POST 请求,并使用 express 在节点中处理它。 我在 iOS 中的代码:

    let boop: [String: AnyObject] = ["username":"fakeuser"];
Alamofire.request(.POST,"http://localhost:3000/test", parameters: boop, encoding: .JSON)

这是我在节点中的代码:

    var app = require('express')();  
var http = require('http').Server(app);  
app.post('/test', function(req, res){
 console.log("THE SERVER HAS RECEIVED THE POST! \n")
 console.log(req.body);
});

http.listen(PORT, function(){
  console.log('listening on *:3000');
});

我的终端控制台打印出“服务器已收到帖子”,所以我知道帖子实际上已被触发。问题是它没有记录 req.body,而是打印出“未定义”。我环顾四周,似乎需要配置“正文解析器”的东西,但显然新版本的 express 已经过时了。所以我不知道该怎么做。

有什么建议吗?

【问题讨论】:

    标签: javascript ios node.js express alamofire


    【解决方案1】:

    我很确定您需要将 body-parser 添加到您的 express 应用以解析 JSON。

    const bodyParser = require('body-parser');
    app.use(bodyParser.json());
    

    http://expressjs.com/de/api.html#req.body

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 2020-12-28
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 2014-04-04
      • 2020-04-13
      • 2023-04-10
      相关资源
      最近更新 更多