[英]Meteor: this.userId and Meteor.userId() both are null within a Meteor Method
为了将这个问题归结为基本问题和最少的代码,我创建了一个普通的新流星应用程序,添加了accounts-password
程序包并添加了以下代码片段。 我的数据库中有一个测试用户。
Meteor.methods({
'testMethod': function() {
console.log('test2:', this.userId); // => null
console.log('test3:', Meteor.userId()); // => null
}
});
if (Meteor.isServer) {
Meteor.publish('testPublication', function() {
console.log('test1:', this.userId); // => 1c8tHy3zb8vP9E5yb
Meteor.call('testMethod');
});
}
if (Meteor.isClient) {
Meteor.loginWithPassword('test', 'test', function() {
Meteor.subscribe('testPublication');
});
}
如您所见,在出版物中, this.userId
包含正确的userId。 但是在流星方法testMethod
, this.userId
和Meteor.userId()
都返回null
。
这是流星虫还是这种方法错误?
这是预期的行为。 这是因为您正在从服务器调用该方法。 服务器上没有用户,因此方法调用obejct( this
)上的userId为null
。 登录后,尝试从客户端调用它。
这是因为您没有从服务器向客户端返回响应。 这是您的操作方式:
methodName: function (arg1, arg2){
//do something with the arguements, maybe throw an error:
if(!Meteor.user()){
//it won't do anything after the error so you don't have to write an else statement
throw new Meteor.Error('You are not a user!');
}
return Meteor.userId()
},
和您在客户端的通话:
Meteor.call('methodName', arg1, arg2, function(err, res){
if(err){
//err is the error you throw in the method
console.log(err)
} else {
//result is what you return from your method
console.log(res)
}
});
Meteor.userId()
可以完美地在方法或客户端使用。
另外,据我所知,发布只能将游标返回到客户端。 您甚至无法返回使用findOne()
找到的对象。
编辑 :
您正在从服务器发布中调用方法,而不会引起任何争论。 如果调用从客户端的方法,从用户帐户,它不会再回来为NULL,或者即使我认为这是错误的,它也可以,如果你作为一个arguement通过this.userId到您当前的工作.call()
在您的发布中,但在该方法中仍不会提供Meteor.userId()。 它将返回您从发布中传递的争论/ ID。
这个怎么样?
function testMethod() {
console.log('test2:', this.userId); // => should be 1c8tHy3zb8vP9E5yb
}
Meteor.methods({
'testMethod': testMethod
});
if (Meteor.isServer) {
Meteor.publish('testPublication', function() {
console.log('test1:', this.userId); // => 1c8tHy3zb8vP9E5yb
testMethod.call(this);
});
}
if (Meteor.isClient) {
Meteor.loginWithPassword('test', 'test', function() {
Meteor.subscribe('testPublication');
});
}
用方法代替
console.log('test2:', this.userId); // => null
console.log('test3:', Meteor.userId()); // => null
用
if(Meteor.user) //USE THIS!
{
console.log('test2:', Meteor.userId()); // => null
console.log('test3:', Meteor.userId()); // => null
}
this.userid在方法中不起作用。 但是,使用Meteor.userId返回调用该方法调用的用户的ID。
经过大量讨论和一些答案之后,流星方法似乎不打算从服务器端调用,并且如果没有从客户端调用,则userId根本不可用。 尽管这根本无济于事,并且框架的行为与直觉相反,但这是Meteor的工作方式。
但是,有一个名为meteor-user-extra
( https://github.com/peerlibrary/meteor-user-extra )的软件包,该软件包使Meteor.userId()
也可以在发布端点函数中工作,并且解决了我的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.