使用 Express.js 和 EJS 访问服务器端功能

问题描述 投票:0回答:3

我正在 Express.js 中使用 EJS 作为模板引擎运行一个测试应用程序。我想访问存储在 .js 文件中的函数以运行服务器端而不是客户端。例如,如果我有:

<%= console.log("I'm in the server console"); %>

服务器捕获控制台输出,如果我有:

<script type="text/javascript"> console.log("I'm in the client-side console"); </script>

现在,如果我有一个为客户端输出相同内容的函数,我可以这样包含它:

<script type="text/javascript" src="/javascripts/clientSideCode.js"> clientSideOutput(); </script>

但是我如何包含一个文件及其函数,以便 EJS 可以执行服务器端代码?看来express中的

public
文件夹仅用于客户端代码。

node.js express ejs
3个回答
1
投票

您可以创建模板可以通过

app.locals
:

访问的辅助函数

0
投票

您可以使用 node.jsSocket.IO 在客户端和服务器之间发出实时事件。例如,客户会这样做:

<script>window onload = function() {

socket.emit('request_customer_list', { state: "tx" });

socket.on('receive_customer_list', function(data) {
$.each(data.customer_list, function(key, value) {

  socket.set(key, value); // store the customer data and then print it later
});

});}

在您的服务器上,您可以有一个例程来加载客户列表并以类似的格式将其发回:

socket.on('connection')
  socket.on('request_customer_list', function(data){
   state = data.state;
   var customer_list;
   // pretend i loaded a list of customers from whatever source right here
   socket.emit('receive_customer_list', {customer_list: customer_list});
)} )};

0
投票

正如 @hunterloftis 所说,辅助函数绝对是正确的选择,然后通过 EJS 访问它。扩展他的答案:

app.js:

clientSideOutput() {
    // Your code
}

const app = express()

app.set('view engine', 'ejs')
app.locals.clientSideOutput= clientSideOutput

Yout template.ejs 文件:

<div>
    Some text, then <%= clientSideOutput() %>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.