我想在id ='name'的html p标签中显示来自nodejs的变量'name'。 html页面何时加载?
view.html
<html>
<head>
<title>TRY</title>
</head>
<body>
<p id="name"></p>
</body>
<script type="text/javascript" src="try.js"></script>
</html>
try.js
var http = require ('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var name = "Ronish";
app.use(express.static('public'));
document.getElementById('name').innerHTML=name;
server.listen('3030');
console.log('Listening on port 3030');
答案 0 :(得分:1)
我想您正在将服务器端js和客户端js混为一谈
document.getElementById('name').innerHTML=name;
以上行在节点js中无效,因为
document
对象是 仅适用于浏览器(客户端js)
如何显示变量? 尝试使用ejs
这样的模板引擎var http = require ('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var name = "Ronish";
app.set('view engine', 'ejs');
app.use(express.static('public'));
server.listen('3030');
console.log('Listening on port 3030');
app.get("/",(req,res)=>{
res.render("index",{"value":name})
})
然后您可以将其显示在index.ejs
文件中
<html>
<head>
<title>TRY</title>
</head>
<body>
<p id="name"><%=value %> </p>
</body>
<script type="text/javascript" src="try.js"></script>
</html>
为您的Reference(表达路由)