【问题标题】:Meteor.userId() not available in ConnectHandlersMeteor.userId() 在 ConnectHandlers 中不可用
【发布时间】:2015-09-21 19:51:21
【问题描述】:

我正在尝试在 Meteor 中创建文件上传功能,其中登录用户能够将文件上传到服务器,该目录下的目录以他们的用户名命名。我有基本的工作,但是当我通过检查登录的用户 ID 更进一步时,事情开始破裂。具体来说:

WebApp.connectHandlers.use('/upload/', function(req, res) {
    if (this.userId) {
        // Do cool stuff.
    } else {
        res.writeHead(500, {"content-type":"text/html"});
        res.end("this.userId = " + this.userId); // End the response.
    }
});

结果:

this.userId = undefined

还有……

WebApp.connectHandlers.use('/upload/', function(req, res) {
    if (Meteor.userId()) {
        // Do cool stuff.
    } else {
        res.writeHead(500, {"content-type":"text/html"});
        res.end("Meteor.userId() = " + Meteor.userId()); // End the response.
    }
});

结果:

Error: Meteor.userId can only be invoked in method calls. Use this.userId in publish functions.
    at Object.Meteor.userId (packages/accounts-base/accounts_server.js:19:1)
    at Object.Package [as handle] (packages/cool_package/upload.js:34:1)
    at next (/Users/me/.meteor/packages/webapp/.1.2.0.19shc3d++os+web.browser+web.cordova/npm/node_modules/connect/lib/proto.js:190:15)
    at Function.app.handle (/Users/me/.meteor/packages/webapp/.1.2.0.19shc3d++os+web.browser+web.cordova/npm/node_modules/connect/lib/proto.js:198:3)
    at Object.fn [as handle] (/Users/me/.meteor/packages/webapp/.1.2.0.19shc3d++os+web.browser+web.cordova/npm/node_modules/connect/lib/proto.js:74:14)
    at next (/Users/me/.meteor/packages/webapp/.1.2.0.19shc3d++os+web.browser+web.cordova/npm/node_modules/connect/lib/proto.js:190:15)
    at Object.WebAppInternals.staticFilesMiddleware (packages/webapp/webapp_server.js:331:1)
    at packages/webapp/webapp_server.js:625:1

上面的代码包含在我正在开发的 Meteor 包中。 package.js 文件指定代码应该在服务器上运行:

api.add_files("upload.js", "server");

所以我的问题是:

  • 查看登录用户 ID 和用户名的正确方法是什么?
  • 能否将此代码移至 Iron Router 路由?

【问题讨论】:

    标签: meteor


    【解决方案1】:

    看起来像这条线

    WebApp.connectHandlers.use('/upload/', function(req, res) {
    

    是 Express.js 还是类似的代码——如果是这样,你已经打破了 Meteor 框架,提供你自己的 REST 服务等。如果是这种情况,你还必须为传入的 REST 提供你自己的用户管理和身份验证方案调用,就像在任何其他基本 REST 应用程序中一样

    【讨论】:

    • 实际上 WebApp.connectHandlers.use 使用 webapp 包的官方流星 API:docs.meteor.com/packages/webapp.html 不过你是对的,在这种情况下必须“手动”编码 auth 的东西。
    猜你喜欢
    • 2014-08-10
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多