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

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

问题描述:

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

I'm sending a file from client-side to server side using 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服务器端并将文件保存到磁盘. 文档似乎只是在谈论客户端处理问题;我什至不知道该如何在服务器端建立一个钩子.

Now I want to respond to this POST server-side and save the file to disk. The docs only seems to talk about handling things client-side; I don't even know how to get a hook on the server-side.

我现在所有的路线都是这样:

All I have for routes right now is this:

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

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

使用连接,我可以做到:

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

铁路由​​器是否有类似的东西?

翻阅内部结构,我发现Meteor正在引擎盖下使用connect,我可以执行以下操作:

Digging through the internals, I discovered Meteor is using connect under the hood, and I can do something like this:

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

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

But I have no idea how to get the user in this context.

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

By default, your routes are created as client side routes. This means, a link to that route will be handled in the browser vs. making a server request. But you can also create server side routes by providing a where option to the route. The handler for the server side route exposes the request, response, and next properties of the Connect object. The syntax has changed a little from 0.5.4 to the dev branch so I'll provide both examples depending on which you're using:

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
    }
  });
});