【问题标题】:using both server and client side rendering using nodejs使用 nodejs 同时使用服务器和客户端渲染
【发布时间】:2019-03-28 11:15:50
【问题描述】:

我是前端开发的新手。我想构建一个同时利用服务器端和客户端渲染的基本应用程序。我正在使用 nodejs 进行服务器端渲染。我不确定为什么我无法将 html 与 javascript 文件一起呈现(与 HTML 外部链接)

index.html:

 <!DOCTYPE html>
 <html>
 <head>
 <title>Display Time and Date </title>
 </head>
<body>
<h1>Welcome</h1>
<p id="dat"></p>
<p id="time"></p>
<script type="text/javascript" src="DisplayDate.js"></script>
</body>
</html>

DisplayDate.js:

var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var hours = date.getHours();
var min = date.getMinutes();
if (min < 10) min = '0' + min;
document.getElementById("dat").innerHTML = "Today\'s Date: " + day +"/" + month + "/" + year ;
document.getElementById("time").innerHTML = "Time: " + hours + ":" + min; }

index.js: ->(服务器端渲染这个文件)

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('./index.html', null, function(err, data) { 
if(err) {
res.write('ERROR')
}
else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
}

res.end();
});
}).listen(process.env.PORT || 8080);
console.log('server-side rendering working fine');

【问题讨论】:

  • 你能在没有 javascript 的情况下加载 html 文件吗?
  • 你可以使用 express 框架来渲染 html 文件
  • @PavanVora 是的,我可以加载 html。我的问题是我只看到标题 (h1) 而不是任何由 DisplayDate.js 设置值的段落
  • 因为只是返回html内容,所以可以打开浏览器的开发者工具,出现错误http://localhost:8080/DisplayDate.js not found。
  • @BhauraoBirajdar 是否可以在不使用任何框架的情况下将 html 与 javascript 一起呈现?我对服务器和客户端渲染的理解是否正确?

标签: javascript node.js


【解决方案1】:

它不起作用,因为您发送的是纯文本,它是静态数据。 你只有两种方式 1. 使用 Express JS 它有res.sendFile() 方法,它会处理文件的链接 2.将你的JS代码放在html页面中

你还有一种方法,但不推荐

<!DOCTYPE html>
<html>
    <head>
        <title>Display Time and Date </title>
    </head>
    <body>
        <h1>Welcome</h1>
        <p id="dat"></p>
        <p id="time"></p>
        <script>
            function loadFile(filename){
                var script=document.createElement('script')
                script.setAttribute("type","text/javascript")
                $.get(filename, (data)=>{
                   script.innerText = data
                   document.getElementsByTagName("head")[0].appendChild(script)
               }) //use AJAX to get your JS code and place it inside new script element you can use XMLHttpRequest i am using JQUERY here

            }       
            loadFile("DisplayDate.js")
        </script>
    </body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多