gpt4 book ai didi

javascript - 从方法/发布外部访问 Meteor.userId

转载 作者:行者123 更新时间:2023-11-30 13:02:52 26 4
gpt4 key购买 nike

我目前正在为 Meteor 编写一个以服务器为中心的包,相关代码如下所示:

__meteor_bootstrap__.app.stack.unshift({
route: route_final,
handle: function (req,res, next) {
res.writeHead(200, {'Content-Type': 'text/json'});
res.end("Print current user here");
return;
}.future ()
});

这显然是一种相对笨拙的做事方式,但我需要创建一个 RESTful API。

如何从这里访问 Meteor.userId()?文档说它只能从方法内部访问或发布。有什么解决办法吗?

我尝试过的事情:

  • 使用 Meteor.publish("user", function() { user = this.userId() });
  • 从发布中捕获它
  • 从 cookie 中获取 token + 用户 ID 并使用类似 Meteor.users.findOne({_id:userId,"services.resume.loginTokens.token":logintoken});
  • 创建一个名为 get_user_id 的方法并从我下面的代码中调用它。

最佳答案

您首先需要定位的是获取可以从 header 中识别用户的内容(特别是因为您希望在无法运行 javascript 的位置获取用户名)。

Meteor 将登录 session 数据存储在 localStorage 中,只能通过 javascript 访问。因此,在页面加载并传递 header 之前,它无法检查谁已登录。

为此,您还需要将用户数据存储为 cookie 以及 localStorage:

客户端 js - 使用来自 w3schools.com 的 cookie setCookiegetCookie 函数

Deps.autorun(function() {
if(Accounts.loginServicesConfigured() && Meteor.userId()) {
setCookie("meteor_userid",Meteor.userId(),30);
setCookie("meteor_logintoken",localStorage.getItem("Meteor.loginToken"),30);
}
});

服务器端路由

handle: function (req,res, next) {
//Parse cookies using get_cookies function from : http://stackoverflow.com/questions/3393854/get-and-set-a-single-cookie-with-node-js-http-server
var userId = get_cookies(req)['meteor_usserid'];
var loginToken = get_cookies(req)['meteor_logintoken'];

var user = Meteor.users.findOne({_id:userId, "services.resume.loginTokens.token":loginToken});

var loggedInUser = (user)?user.username : "Not logged in";

res.writeHead(200, {'Content-Type': 'text/json'});
res.end("Print current user here - " + loggedInUser)
return;
}.future ()

cookie 允许服务器在呈现页面之前检查谁登录了。它会在用户登录后立即设置,使用 Deps.autorun

进行响应

关于javascript - 从方法/发布外部访问 Meteor.userId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16727922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com