纯粹出于教学目的,我在单节点服务器上同时提供前端和后端数据。现在,我已经成功地收到了我的客户端请求,根据所述请求创建了一些数据,能够对其进行控制台日志记录,等等。我的问题是,如果我的数据只是一个用fs库读取的html文件,当我试图在我的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();
}我可以在控制台中看到数据,在最后一种情况下,它只是我的HTML文件。它只是不会在页面中呈现。
发布于 2015-06-26 01:02:15
您是如何尝试使用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>Edit:要与您的代码匹配,请尝试执行以下操作:
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;
}
}发布于 2018-01-27 05:40:38
以异步方式提供html的工作原理是这样的;
var fs = require('fs');
var http = require('http');
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('index.html', function(err, data){
if(err){
return console.log(err);
}
res.end(data);
});
}).listen(8080);
console.log('Server is running on Port: 8080');
https://stackoverflow.com/questions/31056195
复制相似问题