ReferenceError:未在Node.js中定义文档

时间:2019-08-28 10:07:09

标签: javascript html node.js

我想在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');

1 个答案:

答案 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(表达路由)