gpt4 book ai didi

javascript - Node.js In Action Book 回调示例

转载 作者:行者123 更新时间:2023-12-03 02:32:12 24 4
gpt4 key购买 nike

我正在研究《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>

最佳答案

res.writeHead(200, { 'Content-Type': 'text/html' });< 之后缺少 res.end(html);/p>

不包含res.end意味着服务器将完成对请求的处理,但不会告诉浏览器结果,因此浏览器将无限期地等待响应。

关于javascript - Node.js In Action Book 回调示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48691532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com