如何使用Meteor和Iron-Router响应服务器端的路由?

时间:2013-08-31 04:27:12

标签: meteor iron-router

我正在使用XHR从客户端向服务器端发送文件:

$(document).on('drop', function(dropEvent) {
    dropEvent.preventDefault();
    _.each(dropEvent.originalEvent.dataTransfer.files, function(file) {
        // ...
        xhr.open('POST', Router.routes['upload'].path(), true);
        xhr.send(file);
    });
})

现在我想响应这个POST服务器端并将文件保存到磁盘。 The docs似乎只谈论处理客户端的事情;我甚至不知道如何在服务器端获得一个钩子。

我现在拥有的所有路线都是:

Router.map(function() {
    this.route('home', {
        path: '/'
    });

    this.route('upload', {
        path: '/upload',
        action: function() {
            console.log('I never fire');
        }
    });
});

使用connect,我可以这样做:

Connect.middleware.router(function(route) {
    route.post('/upload', function(req, res) {
        // my server-side code here
    });
});

Iron-Router是否有类似内容?


通过内部挖掘,我发现Meteor正在使用connect,我可以这样做:

WebApp.connectHandlers.use(function(req, res, next) {
    if(req.method === 'POST' && req.url === '/upload') {
        res.writeHead(200);
        res.end();
    } else next();
});

但我不知道如何在这种情况下吸引用户。

4 个答案:

答案 0 :(得分:5)

默认情况下,您的路由被创建为客户端路由。这意味着,将在浏览器中处理指向该路由的链接,而不是发出服务器请求。但您也可以通过为路由提供where选项来创建服务器端路由。服务器端路由的处理程序公开request对象的responsenextConnect属性。语法从0.5.4略微改变为dev分支,因此我将根据您使用的内容提供两个示例:

<强> v0.5.4

Router.map(function () {
  this.route('upload', {
    where: 'server',
    handler: function () {
      var request = this.request;
      var response = this.response;
      // do whatever
    }
  });
});

<强> dev的

Router.map(function () {
  this.route('upload', {
    where: 'server',
    action: function () {
      var request = this.request;
      var response = this.response;
      // do whatever
    }
  });
});

答案 1 :(得分:1)

您可以使用EJSON和普通流星​​“方法”上传文件,这样您就可以访问用户数据,因为它只在方法内部可见,并且在服务器端发布功能

此视频教程可能是good start

CollectionFS也提供了一些上传功能。它现在很少过时,但想法保持不变。

答案 2 :(得分:1)

为您带来铁路由器的人也有meteor-file可以为您进行文件传输,或者您可以将其作为自己实现的示例

答案 3 :(得分:0)

Meteor Router(现已弃用)具有服务器端路由支持:

Meteor.Router.add('/upload', 'POST', function() {
  // do stuff
});
相关问题