【问题标题】:Meteor - Parse Data from Incoming HTTP RequestMeteor - 从传入的 HTTP 请求中解析数据
【发布时间】:2013-12-21 17:37:36
【问题描述】:

对于传出的 HTTP 请求(使用meteor.http.call),我可以定义参数和/或数据。然后可以使用结果(通过 results.content)。

如何访问和解析传入 HTTP 请求的正文/内容/数据?

使用 Iron-router,我已经做到了:

Router.map(function () {
this.route('httpTest', {
path: '/httpTest',
action: function () {
  var request = this.request;
  var response = this.response;      
  console.log('request_body: '+ request.body);
  // request.body does not work.  what should it be????

注意我知道我可以访问查询参数,但我想从传入的 http 请求的正文中访问表单数据和/或 json 数据。

【问题讨论】:

    标签: parsing http meteor iron-router


    【解决方案1】:

    为了读取原始正文,无需 Node.js 对其进行 JSON 化,以同步方式,我使用了这个:

    Router.route("my/api", function() {
        var rawBody = "";
        var chunk;
        while ((chunk = this.request.read()) !== null) {
            rawBody += chunk;
        }
    }, { where: "server" });
    

    (此处另一个答案中提出的异步方式对我不起作用,尽管它应该根据 Node.js 文档)。

    【讨论】:

      【解决方案2】:

      由于缺少where: 'server',它可能无法正常工作。这是一个工作示例:

      Router.map(function() {
        this.route('test', {
          where: 'server',
          action: function() {
            console.log(this.request.body.make);
            console.log(this.request.body.model);
            this.response.writeHead(200, {'Content-Type': 'text/html'});
            this.response.end('hello!\n');
          }
        });
      });
      

      从命令行我可以使用:

      curl -X POST -H "Content-Type: application/json" -d '{"make":"honda","model":"civic"}' http://localhost:3000/test
      

      在服务器终端中打印预期的hondacivic。看起来this.request.body 已经被解析,因此您可以直接访问任何变量,如果您的输入是 json,这很好。

      【讨论】:

      • this.request.body.make 不再起作用,this.request.make
      【解决方案3】:

      请求是incoming http message,也就是Readable Stream,所以你可以通过从那个流中读取来获取请求的数据。

      以下应该可以工作(但我还没有测试过):

      var readable = this.request;
      var alldata = "";
      readable.on('data', function(chunk) {
        alldata += chunk;
      })
      readable.on('end', function() {
        console.log('do something with alldata');
      });
      

      【讨论】:

      • 这很有帮助,并已将我指向节点文档。但是上面的代码返回“无法调用未定义 route.action 的方法'on'”有什么线索吗?谢谢
      • 正如大卫指出的那样,您缺少“where;'server'”,因此您似乎在客户端上执行此操作,其中 this.request 确实未定义,因为错误是在这里告诉你。
      • 是的,这两种方法都可以解决——我接受了大卫的回答,因为我确实收到了 json,而且这种方法简单直观。非常感谢
      • 在我的例子中,“end”事件不会被触发:可能是因为在发出 readable.on("end") 之前流被消耗掉了?
      猜你喜欢
      • 1970-01-01
      • 2015-10-18
      • 2021-01-18
      • 1970-01-01
      • 2016-08-04
      • 1970-01-01
      • 1970-01-01
      • 2018-07-30
      • 2016-04-23
      相关资源
      最近更新 更多