使用 NodeJs 作为服务器端,使用 ejs 模板作为前端来处理前端和后端。使用ejs scriplets时遇到一个功能加载页面时显示从服务器发送的数据。
二手<%console.log()%>
通过 ejs,认为此日志将在检查元素日志中看到,但是通过服务器终端收到消息。在没有任何表单提交或 API 调用的情况下,这些信息是如何发送到服务器的?
服务器app.js:
/*jshint multistr: true, node: true, esversion: 6, undef: true, unused: true, varstmt: true*/
"use strict";
// NPM Modules
const express = require('express'),
path = require('path');
const app = express();
// Setup views directory, file type and public filder.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.render('index', {message:'Welcome'});
});
const port = process.env.PORT || 3000;
console.log('server listening at http://127.0.0.1 over port: ', port);
app.listen(port);
EJS模板index.ejs:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<!-- All these CSS files are in plublic directory, as we had made all the content of public directory available for anyone from app.js -->
<link rel="stylesheet" type="text/css" href="/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/css/app.css" />
<link rel="shortcut icon" href="logo.jpg" />
<title>Sign-Up/Login Form</title>
</head>
<body>
<%console.log(message)%>
<%=message%>
<%console.log("anything")%>
</body>
</html>
如何才能全部 <%console.log()%>
通过服务器终端发送和 <%=message%>
显示在浏览器上。偶<%console.log("anything")%>
即使这与服务器无关,也会显示在服务器终端上。 ejs scriplet 如何与服务器而不是浏览器通信?
之前是否有其他人尝试过或观察过它。
最佳答案
您的问题是关于 ejs 模板如何工作的。这是该问题的答案。我认为您的快速设置也可能出现一些奇怪的情况,从而导致出现问题。
EJS 是一个服务器端渲染系统。它的工作是在 html 发送到客户端之前完成的,因此与浏览器无关。
<% %>
内的脚本在服务器上运行,在发送到客户端之前将内容插入到模板中。
如果您想在浏览器控制台上打印一些内容,请不要将其放入 scriptlet 中,只需将其放入 <script>
中即可。标签,像这样:
<script>
console.log("foo");
</script>
如果您希望浏览器控制台打印服务器生成的内容,您可以使用 ejs 将消息的值放入其生成的内容中:
<script>
console.log("<%=message%>");
</script>
服务器会将消息的值放入 console.log() 语句中,然后传递给浏览器。
此示例将“Wellcomes”打印到浏览器控制台:
服务器:
const bodyParser = require('body-parser'),
express = require('express'),
path = require('path');
const app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', (req, res) => {
res.render('index', { message: 'Wellcomes' });
});
const port = process.env.PORT || 3000;
const listener = app.listen(port, function() {
console.log('platform listening on', listener.address().port);
});
索引.ejs:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sign-Up/Login Form</title>
</head>
<body>
<script>
console.log("<%=message %>");
</script>
</body>
</html>
如果您在浏览器中显示页面源代码,您应该会看到:
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Sign-Up/Login Form</title>
</head>
<body>
<script>
console.log("Wellcomes");
</script>
</body>
</html>
关于html - ejs模板是如何加载到浏览器上的?前端如何与后端交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53025160/