【问题标题】:HTTP post call from Template.event to a route in iron:router + meteor从 Template.event 到 iron:router + meteor 中的路由的 HTTP 发布调用
【发布时间】:2015-07-03 08:06:00
【问题描述】:

我想在流星中使用来自 Template.event 的 post 参数进行 HTTP.call。我已经在 Iron:Router 中定义了我当前应用程序的路由。 路线正在接听电话,但我无法获取发布参数。该路由是服务器端路由,并使用以下命令返回 pdf 内容:

Template.eStatement.events({
    'click .pdf': function (event, template){ 
         event.preventDefault(); 
         param = Some json object that I need to pass as post parameter.
         HTTP.call("POST", '/statement', JSON.stringify(param), 
         function(error, result){ if(result){ // } if(error){ // } //done(); }); }}); 

这是我的路线(我正在使用 iron:route 包为流星)

Router.route('/statement', function () { 
var param = JSON.parse(this.params.query.param); 
/** Get the pdf content by calling the api 
/** Write the content back : 
this.response.writeHeader('200', { 
'Content-Type': 'text/html', 
'Content-Disposition': "inline", 
});
this.response.write('pdfcontent');
this.response.end(); },{where: 'server'}

【问题讨论】:

  • 请输入代码。不看代码就很难帮助排错。
  • 这很难读。请编辑您的帖子,并阅读如何在 StackOverflow 上的帖子中格式化代码。 (选择您的代码并点击 { } 大括号图标)。
  • 对不起。这是我关于堆栈溢出的第一篇文章。不习惯格式化。
  • 我希望编辑后的帖子足够清晰。
  • 您能告诉我您将在HTTP.call 中使用哪些(或多少个)参数吗?

标签: meteor


【解决方案1】:

试试这样的方法:

在客户端:(在客户端/文件夹内)

Template.eStatement.events({
  'click .pdf': function (event, template) {
    var params = {
      something: 'abcdef',
      someOption: true
    };
    HTTP.call('POST', '/statement', {
      data: params
    }, function (error, result) {
      console.log('http callback');
      console.log(error);
      console.log(result);
    });
  }
});

在服务器上:(在 server/ 文件夹内)

Router.route('/statement', {
  where: 'server',
  action: function () {
    var params = this.request.body;

    // do something with params

    this.response.writeHeader('200', {
      'Content-Type': 'text/html',
      'Content-Disposition': "inline"
    });
    this.response.write('pdfcontent');
    this.response.end();
  }
});

请记住,在路由中,this.request.body 在这种情况下是一个对象,而不是字符串。所以你不需要使用JSON.stringifyJSON.parse 来处理它。

【讨论】:

  • 非常感谢。我能够获取帖子参数。
猜你喜欢
  • 2015-02-12
  • 2017-12-03
  • 2016-12-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-25
  • 1970-01-01
  • 2016-01-16
相关资源
最近更新 更多