NodeJS 为什么当我转到localhost链接时屏幕上没有文本

2admgd59  于 2023-03-17  发布在  Node.js
关注(0)|答案(2)|浏览(81)
const http = require('http');
const fs = require('fs');
const port = 3000;

const server = http.createServer(function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    fs.readFile('home.html', function(err, data) {
        if (err) {
            res.writeHead(404);
        }
        else {
            res.write(data);
        }
    });
    res.end();
});

server.listen(port, function(error) {
    if (error) {
        console.log(error);
    }
    else {
        console.log('Server is listening on port ' + port + ' at http://localhost:' + port);
    }
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    Hello

</body>
</html>

当我运行这个并进入本地服务器时,屏幕上没有文本,甚至认为它应该说“你好”,因为这是我在homeiderhtml文件中写的
我今天刚刚安装了node js,不知道它是如何工作的,但我仍然认为这应该工作

nbysray5

nbysray51#

您在fs.readFile回调之外调用res.end,该回调发出请求结束的信号,并且它在您完成阅读/写入文件之前向用户发送响应

const server = http.createServer(function (req, res) {
  fs.readFile("./home.html", function (err, data) {
    if (err) {
      res.writeHead(404);
      console.log(err);
    } else {
      res.writeHead(200, { "Content-Type": "text/html" });
      console.log(data);
      res.write(data);
    }
    res.end();
  });
});
nbnkbykc

nbnkbykc2#

你在写入数据之前结束了响应。
下面是一个完整的工作代码:

const http = require('http');
const fs = require('fs');
const port = 3000;

const server = http.createServer(function(req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    fs.readFile('home.html', function(err, data) {
        if (err) {
            res.writeHead(404);
        }
        else {
            res.write(data);
        }
    res.end();
    });
});

server.listen(port, function(error) {
    if (error) {
        console.log(error);
    }
    else {
        console.log('Server is listening on port ' + port + ' at http://localhost:' + port);
    }
});

相关问题