从节点服务器提供HTML文件
几乎完全出于教学目的,我使用单节点服务器提供前端和后端数据。现在,我已经成功地收到了我的客户请求,根据所述请求创建了一些数据,能够对其进行控制台日志记录,等等。到目前为止,一切都很好。我的问题是,如果我的数据只是一个html文件,而该文件是通过fs库读取的,那么当我试图在res.end()或res.write()中提供数据时,它将不会呈现在页面上。当我在控制台上记录它时,我可以看到它正是我想要和期望的,但它只是不在浏览器中呈现。任何帮助都将不胜感激。我已经将其设置为在“if/else”中处理请求,其中我只有两个场景“/”(home),在这种情况下,我提供html文件和其他任何内容,因为服务器实际上只需要处理这两个事件。提前谢谢 编辑。这就是我到目前为止所做的:从节点服务器提供HTML文件,html,node.js,file,server,Html,Node.js,File,Server,几乎完全出于教学目的,我使用单节点服务器提供前端和后端数据。现在,我已经成功地收到了我的客户请求,根据所述请求创建了一些数据,能够对其进行控制台日志记录,等等。到目前为止,一切都很好。我的问题是,如果我的数据只是一个html文件,而该文件是通过fs库读取的,那么当我试图在res.end()或res.write()中提供数据时,它将不会呈现在页面上。当我在控制台上记录它时,我可以看到它正是我想要和期望的,但它只是不在浏览器中呈现。任何帮助都将不胜感激。我已经将其设置为在“if/else”中处理请求
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的
我刚刚在这里做了一个小测试,结果如下:
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);
hello-world.html
<h3>Hello World</h3>
以异步方式提供html的工作原理是这样的
var fs=require('fs');
var http=require('http');
http.createServer(函数(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
fs.readFile('index.html',函数(err,data){
如果(错误){
返回console.log(err);
}
res.end(数据);
});
}).听(8080);
log('服务器正在端口8080上运行')代码>我刚刚编辑了我的答案以与您的代码相匹配,看看是否有帮助。:)
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;
}
}