我正在 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 和 Socket.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});
)} )};
正如 @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>