[英]NodeJS web server, issues loading an html file when the server is started
好的,基本上我正在使用Node构建一个JavaScript开发应用程序。 我不断出现的问题是服务器何时启动。
var host = '127.0.0.1',
port = 8080;
var fs = require('fs'),
http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var buffer = new Buffer(100);
res.end(fs.read('index.html'));
}).listen(port, host);
console.log('Server running at http://' + host + ':' + port);
我的问题在于res.end(fs.read('index.html')); 我希望服务器在浏览器中建立连接时运行该html文档。 我总是在控制台中收到此错误响应。
buffer.js:236
throw new Error('First argument needs to be a number, ' +
Error: First argument needs to be a number, array or string.
at new Buffer (buffer.js:236:15)
at Object.fs.read (fs.js:348:14)
at Server.<anonymous> (C:\Users\myname\Desktop\app\bin\server.js:45:20)
at Sever.EventEmitter.emit (events.js:96:17)
at HTTPParser.parser.onIncoming (http.js:1807:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:111:23)
at Socket.socket.ondata (http.js:1704:22)
我的问题是,当与服务器建立连接时,如何在Web浏览器中显示html文档? 任何帮助表示赞赏。 谢谢。
您的代码提出了一些问题,但如果我了解您的要求,则这就是您所需要的:
您需要将文件的结果写入响应流,如下所示。
var host = '127.0.0.1',
port = 8080;
var fs = require('fs'),
http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('index.html',function(err,data){
res.write(data);
res.end();
});
}).listen(port, host);
console.log('Server running at http://' + host + ':' + port);
当然,这没有错误检查等,但会让你去。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.