从节点服务器提供HTML文件

spb*_*spb 4 html file node.js server

几乎纯粹出于教学目的,我从我的一个节点服务器提供我的前端和后端数据.现在,我正处于成功接收客户端请求的位置,根据所述请求创建了一些数据,能够控制日志,等等.到目前为止一切都很好.我的问题是,如果我的数据只是一个html文件,正在用fs库读取,当我尝试在我的res.end()或res.write中提供它时,它不会在页面上呈现().我可以看到它正是我想要和控制日志时所期望的,但它不会在浏览器中呈现.任何帮助,将不胜感激.我已将它设置为我在"if/else"处理我的请求的位置,其中我只有两个场景"/"(home),在这种情况下我提供html文件,以及其他任何因为服务器真的只需要处理这两个事件.提前致谢.

编辑.这是我到目前为止:

function responseHandler(req, res) {
 res.writeHead(200, {"Content-Type": "text/html"});
 if (req.url.match("fav")) {
   res.end("");
   return;
 }
 else if (req.url.match("/endpoint")) {
   var input = req.url.match(/endpoint\/(.*)/)[1];
   var output = endpoint.toHTML(decodeURI(input));
   res.end(data);
   console.log(input, req.url)
 }
 else {
   fs.readFile("index.html", "utf8", function(err, data) {
     console.log("data:" + data);
     var input = req.url.match(/endpoint\/(.*)/)[1];
     var output = endpoint.toHTML(decodeURI(input));
   });
 }

 res.end();
}
Run Code Online (Sandbox Code Playgroud)

我可以在控制台中看到数据,在最后一种情况下,它只是我的HTML文件.它只是不会在页面中呈现.

Dei*_*idy 5

你是怎么尝试用res.end()和提供html的res.write()

我刚刚在这里做了一个小测试,这个工作:

app.js

var http = require('http');
var fs = require('fs');

var html = fs.readFileSync('hello-world.html');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(html);
}).listen(8000);
Run Code Online (Sandbox Code Playgroud)

你好,world.html

<h3>Hello World</h3>
Run Code Online (Sandbox Code Playgroud)

编辑:要与您的代码匹配,请尝试以下操作:

function responseHandler(req, res) {
    res.writeHead(200, {"Content-Type": "text/html"});

    if (req.url.match("fav")) {
        res.end("");
        return;
    } else if (req.url.match("/endpoint")) {
        var input = req.url.match(/endpoint\/(.*)/)[1];
        var output = endpoint.toHTML(decodeURI(input));

        console.log(input, req.url);

        // we have no data variable in this scope
        res.end("");

        // I added a return statement in each step
        // Just to be clear that we don't want to go if any
        // condition have fit, since we cannot call res.end()
        // more than once
        return;
    } else {
        fs.readFile("index.html", "utf8", function(err, data) {
            // error handling
            if (err) return res.end(err);

            // now we have the data
            console.log("data:" + data);
            res.end(data);
        });

        return;
    }
}
Run Code Online (Sandbox Code Playgroud)