我一直关注this tutorial关于nodejs的介绍,但我在使用response.write()返回内容时遇到了问题。
我的server.js代码在返回" hello world"当我转到域:8001,但导航到域:8001 / socket.html返回一个空白屏幕。
我已经使用console.log来检查写入" socket的代码是否在这里。"正在执行,但我不确定为什么它没有做任何事情。
server.js:
var http = require("http");
var url = require('url');
var fs = require('fs');
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
console.log(__dirname);
console.log(path);
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '/socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write("socket is here.");
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
break;
}
response.end();
});
server.listen(8001);
var io = require('socket.io').listen(server);
socket.html :(虽然它不应该包含在其中的内容)
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
var socket = io.connect();
</script>
<div>This is our socket.html file</div>
</body>
</html>
答案 0 :(得分:1)
您在等待fs.readFile()
完成之前结束了回复。试试这个:
var http = require("http");
var url = require('url');
var fs = require('fs');
var server = http.createServer(function(request, response){
console.log('Connection');
var path = url.parse(request.url).pathname;
console.log(__dirname);
console.log(path);
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '/socket.html':
fs.readFile(__dirname + path, function(error, data){
if (error){
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else{
response.writeHead(200, {"Content-Type": "text/html"});
response.write("socket is here.");
}
response.end();
});
return;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
break;
}
response.end();
});
server.listen(8001);
var io = require('socket.io').listen(server);
此外,执行fs.readFile(__dirname + path, ...);
可能会有危险,因为有人可能会发送/../../../../../../etc/passwd
之类的请求。你应该在那里做的是使用path
模块来解析/标准化__dirname + path
到绝对路径,然后确保该绝对路径以公共目录的绝对路径开始。