简体   繁体   English

与客户端脚本nodejs共享模块功能

[英]Share module function with client side script nodejs

I made a function to check if someone is logged in on the site in the user controller module: 我做了一个检查用户控制器模块中是否有人登录的功能:

exports.isLoggedIn = function(req, res, next) {
    if (req.user) {
        return true;
    } else {
        return false;
    }
};

I have no idea how I want to use this in a imported script on the client side. 我不知道如何在客户端的导入脚本中使用它。 I couldn't find a good solution on the web so I thought I would ask the question myself. 我在网上找不到一个好的解决方案,所以我想我自己问这个问题。

If I import the script in the .html I get an error that says it doesnt know the require() function that node has. 如果将脚本导入.html,则会收到错误消息,提示它不知道该节点具有的require()函数。

I hope someone can help me :) 我希望有一个人可以帮助我 :)

If you want client access to some data that is only available on the server, then you need to send an ajax call from the client to your server and you need to create a route on your server to respond to that ajax call. 如果希望客户端访问仅在服务器上可用的某些数据,则需要将ajax调用从客户端发送到服务器,并且需要在服务器上创建路由以响应该ajax调用。

Client code runs only on the client and has no direct access to any data on the server. 客户端代码仅在客户端上运行,无法直接访问服务器上的任何数据。

Server code runs only on the server and has no direct access to any data on the client. 服务器代码仅在服务器上运行,无法直接访问客户端上的任何数据。

To communicate between the two, you have to send a request from one to the other and then return a response. 要在两者之间进行通信,您必须将请求从一个发送到另一个,然后返回响应。 Usually this is done with an Ajax call sent from client to server. 通常,这是通过从客户端发送到服务器的Ajax调用完成的。 You could also establish a webSocket connection between the two and then either client or server could send data to the other. 您还可以在两者之间建立webSocket连接,然后客户端或服务器可以将数据发送到另一个。

The server also has the opportunity, when creating the original page content, to embed settings or values in the page itself, either as Javascript variables, as HTML values or even as a cookie. 在创建原始页面内容时,服务器还可以将设置或值作为Javascript变量,HTML值甚至Cookie嵌入到页面本身中。 This obviously has to be done ahead of time when the page is rendered so it can't be a request that the client comes up with later after the page has been rendered to the client. 显然,这必须在呈现页面时提前完成,因此在将页面呈现给客户端之后,不能要求客户端稍后提出。


FYI, in the particular example you show, it is common for a client to be able to tell if it is logged in via some state in the page (either the presence of a particular cookie) or something else embedded in the page by the server. 仅供参考,在您显示的特定示例中,客户端通常能够判断客户端是否通过页面中的某些状态(存在特定的cookie)或服务器在页面中嵌入的其他内容进行登录。 This isn't necessarily secure and isn't the way the server would tell if a request was logged in, but it usually suffices for client-side logic to decide how it wants to behave. 这不一定是安全的,也不是服务器告知请求是否已登录的方式,但通常它足以满足客户端逻辑来决定其行为方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM