从节点服务器提供HTML文件

纯粹出于教学目的,我正在为我的一个节点服务器提供前端和后端数据。 现在,我已经成功接收到我的客户端请求,根据请求创build了一些数据,能够进行控制台日志logging等等。到目前为止,一切正常。 我的问题是,如果我的数据只是一个html文件,正在用fs库读取,当我尝试在res.end()或res.write ()。 我可以看到这正是我想要和期望的时候,我的控制台login,但它只是不会在浏览器中呈现。 任何帮助,将不胜感激。 我已经把它设置在我在“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(); } 

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

你是怎么试图用res.end()res.write()来提供html的?

我在这里做了一个小testing,这个工作:

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); 

你好,world.html

 <h3>Hello World</h3> 

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

 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; } }