我对Node.js很新。我正在探索路由(代码如下所示)。当客户端请求本地页面(在本例中为socket.html)时,客户端不会获取路由页面,而是显示空白页面。我没有看到Node.js框架的任何错误。 谢谢你看。
var http = require("http");
var url = require('url');
var fs = require('fs');
var io = require('socket.io');
var path = '';
var server = http.createServer(function(request, response){
console.log('Connection');
path = url.parse(request.url).pathname;
console.log(path);
switch(path){
case '/':
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('hello world');
break;
case '/socket2.html':
fs.createReadStream(__dirname + path, function(error, data){
if (error) {
console.log('there is error for ' + path);
response.writeHead(404);
response.write("opps this doesn't exist - 404");
}
else {
console.log('sending file ' + data);
response.writeHead(200, { 'Content-Type': 'text/html' });
response.write(data);
}
});
break;
default:
response.writeHead(404);
response.write("opps this doesn't exist - 404");
break;
}
console.log('send reponse');
response.end();
});
console.log('Listening');
server.listen(8001);
console.log('Socket started for ' + path);
io.listen(server);
// socket2.html页面内容
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>
</head>
<body>
<script>
var socket = io.connect();
</script>
<div>This is our socket2.html file</div>
</body>
</html>
//实际页面内容
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD>
<META http-equiv="Content-Type"
content="text/html; charset=windows-1252"></HEAD>
<BODY></BODY></HTML>
答案 0 :(得分:2)
请查看catberry.js或express框架。
我确信没有人使用节点内置HTTP服务器和切换操作符解决此任务。 也许您只需要一个单独的Web服务器,如nginx,它提供静态服务并将一些位置传递给node.js应用程序以呈现一些动态页面。