Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Node.js在Action Book回调示例中的应用_Javascript_Html_Json_Node.js - Fatal编程技术网

Javascript Node.js在Action Book回调示例中的应用

Javascript Node.js在Action Book回调示例中的应用,javascript,html,json,node.js,Javascript,Html,Json,Node.js,我正在使用book Node.js in action第二版。在第30页有一个回调示例,您在html中使用DisplayJSON,我下面的代码没有运行,我不知道为什么。我正在使用命令节点在适当的目录下运行下面的代码。\blog\u recent.js但当我点击localhost:8000时,它在浏览器中没有做任何事情 NodeJS HTML 您缺少res.endhtml;在res.writeHead200之后,{'Content-Type':'text/html'} 不包括res.end意味着服

我正在使用book Node.js in action第二版。在第30页有一个回调示例,您在html中使用DisplayJSON,我下面的代码没有运行,我不知道为什么。我正在使用命令节点在适当的目录下运行下面的代码。\blog\u recent.js但当我点击localhost:8000时,它在浏览器中没有做任何事情

NodeJS

HTML

您缺少res.endhtml;在res.writeHead200之后,{'Content-Type':'text/html'}

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

 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');
    [
    "Kazakhstan is a huge country.... what goes on there?",
    "This weather is making me craaazy",
    "My neighbor sort of howls at night"
    ]
<!doctype html>
<html>
<head></head>
<body>
    <h1>Latest Posts</h1>
    <ul><li>%</li></ul>
</body>
</html>