[英]Node.js In Action Book callbacks example
I am working with the book Node.js in action second edition. 我正在使用《 Node.js在行动》第二版。 On page 30 there is a callback example where you use display json in html the code I have below is not running and I am not sure why.
在第30页上,有一个回调示例,其中您在HTML中使用display json,我下面的代码未运行,我不确定为什么。 I am running the code below in the proper directory using the command node .\\blog_recent.js but it is not doing anything in the browser when I hit localhost:8000
我正在使用命令节点。\\ blog_recent.js在适当的目录中运行以下代码,但是当我按下localhost:8000时,它在浏览器中没有执行任何操作
NodeJS
的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
JSON
[
"Kazakhstan is a huge country.... what goes on there?",
"This weather is making me craaazy",
"My neighbor sort of howls at night"
]
HTML
HTML
<!doctype html>
<html>
<head></head>
<body>
<h1>Latest Posts</h1>
<ul><li>%</li></ul>
</body>
</html>
you are missing res.end(html);
您缺少
res.end(html);
after res.writeHead(200, { 'Content-Type': 'text/html' });
在
res.writeHead(200, { 'Content-Type': 'text/html' });
not including the res.end
means that the server will finish working on the request but won't tell the browser the result, therefor the browser is waiting for a response indefinitely. 不包含
res.end
意味着服务器将完成请求处理,但不会告诉浏览器结果,因此浏览器将无限期地等待响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.