【问题标题】:'end' undefined for this.response in Iron Router for Meteor'end' undefined for this.response in Iron Router for Meteor
【发布时间】:2015-12-31 02:52:17
【问题描述】:

我已经使用 Iron Router 为我的 Meteor 服务器创建了一个 HTTP POST 端点。我想用状态的 JSON 和一些其他元数据将响应发送回请求者。

这里是端点的代码:

Router.route('/new_video', {where: 'server'})
.post(function(){

    var body = this.request.body;
    this.response.setHeader('Content-Type', 'application/json');

    var filename = body.filename;


    console.log('New video uploaded for: ' + filename);

    Meteor.call('newUpload', filename, function(error, results){
        if (error){
            throw new Meteor.Error("new-video-upload-failed", "New video could not be uploaded.");
            var message = {
                url: '/new_video',
                status: 'success'
            };
        }
        else{
            var videoId = results;
            console.log('Returned video id: ' + videoId);
            var message = {
                url: '/new_video',
                status: 'failure'
            };
        }

        this.response.end(JSON.stringify(message));
    });
});

Meteor 控制台正在打印:

=> Meteor server restarted
I20151002-15:51:26.311(-4)? New recording for: 1422776235,43.46756387,-80.54130886.mp4
I20151002-15:51:26.515(-4)? Returned video id: QiHXxZSb2sn9aNRPs
I20151002-15:51:26.569(-4)? Exception in delivering result of invoking 'newRecording': TypeError: Cannot call method 'end' of undefined
I20151002-15:51:26.569(-4)?     at shared/routes.js:79:17

【问题讨论】:

    标签: meteor iron-router


    【解决方案1】:

    由于Meteor.call中引入了另一个函数回调,导致this的值被修改是JS的一个常见陷阱。

    如果您使用的是带有 ES2015 箭头函数的 Meteor 1.2,您可以使用此函数声明语法来解决该问题:

    Meteor.call('newUpload', filename, (error, results) => {
      // here 'this' will keep referencing the POST route context
      // so you can safely use this.response
    });
    

    如果您不使用 Meteor 1.2,请改用以下语法:

    Meteor.call('newUpload', filename, function(error, results) {
      // inner function is bound to parent function 'this'
    }.bind(this));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 2013-11-21
      • 1970-01-01
      • 2023-03-12
      • 2022-12-27
      • 2017-06-17
      相关资源
      最近更新 更多