【问题标题】:Node.js In Action Book callbacks exampleNode.js In Action Book 回调示例
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-19
      • 2015-01-27
      • 2019-11-05
      • 2011-04-24
      • 1970-01-01
      • 1970-01-01
      • 2018-01-23
      • 1970-01-01
      相关资源
      最近更新 更多