我编写了一个简单的 HTTP 服务器来提供一些 HTML。 代码如下:
var http = require('http');
http.createServer(function(req, res) {
res.writeHeader(200, {"Content-Type": "text/html"});
var html = '<DOCTYPE!>' +
' <html>' +
' <head>' +
' <title>' +
' Test page' +
' </title>' +
' </head>' +
' <body>' +
' <p>' +
' This is a test page !' +
' </p>' +
' </body>' +
' </html>';
res.write(html);
res.end();
}).listen(8080);
生成的 HTML 页面如下:
<html>
<head>
</head>
<body>
<doctype!>
<title> Test page </title>
<p> This is a test page ! </p>
</doctype!>
</body>
</html>
所以我的问题如下:
- 为什么 html“字符串”包含在 HTML 正文中?
- 除了使用模板引擎(jade)之外,是否可以在 HTML 中进行缩进?
最后一个问题有点独立:
- 如果我有一个名为
index.html
的页面,它只显示img.jpg
。我如何知道用户对img.jpg
的请求与index.html
相关? 我所说的“相关”是指:“img.jpg
是index.html
的链接/依赖项”。
提前谢谢您!
最佳答案
Why is the html "string" included in the body of the HTML ?
那是因为<DOCTYPE!>
无效。应该是:
<!DOCTYPE html>
事实上,它对于浏览器来说更像是一个元素,它尝试标准化标记并将其放入 <body>
中。 .
Is it possible to have indentation in the HTML besides using a template engine (jade) ?
许多模板引擎,包括 Jade,实际上 minify标记,删除所有不必要的空白以减少带宽消耗。
但是,您可以考虑使用“美化器”,例如 html .
If I have a page called index.html which only shows img.jpg. How can I know that a users request to img.jpg is related to index.html ? What I mean by "related" is : "that img.jpg is a linked / a dependency of index.html".
您可以在大多数浏览器内调试器中查看“资源”,其中将列出您的页面请求的图像、脚本、样式表等。
您也可以尝试web scraping您的应用程序,也许带有 jsdom :
jsdom.env('http://localhost:8080/', [
'http://code.jquery.com/jquery.min.js'
],
function (err, window) {
var $ = window.$;
var hrefs = $('a[href]').map(function () {
return $(this).attr('href');
}).get();
console.log(hrefs);
});
关于javascript - 正文中的 Node HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12291642/