【发布时间】:2018-02-08 17:35:08
【问题描述】:
我正在研究 Node.js in action 第二版这本书。在第 30 页有一个回调示例,您在 html 中使用显示 json,我下面的代码没有运行,我不知道为什么。我正在使用命令 node .\blog_recent.js 在正确的目录中运行下面的代码,但是当我点击 localhost:8000 时它在浏览器中没有做任何事情
NodeJS
const http = require('http');
const fs = require('fs');
http.createServer((req,res) => {
if (req.url == '/') {
fs.readFile('./titles.json', (err, data) => {
if (err) {
console.error(err);
res.end('Server Error');
} else {
const titles = JSON.parse(data.toString());
fs.readFile('./template.html', (err,data) => {
if (err) {
console.error(err);
res.end('Server Error');
} else {
const tmpl = data.toString();
const html = tmpl.replace('%', titles.join('</li><li>'));
res.writeHead(200, { 'Content-Type': 'text/html' });
}
});
}
});
}
}).listen(8000, 'localhost');
json
[
"Kazakhstan is a huge country.... what goes on there?",
"This weather is making me craaazy",
"My neighbor sort of howls at night"
]
HTML
<!doctype html>
<html>
<head></head>
<body>
<h1>Latest Posts</h1>
<ul><li>%</li></ul>
</body>
</html>
【问题讨论】:
标签: javascript html json node.js