尝试连接本地快速服务器时“无法获取/”

时间:2014-03-03 03:35:30

标签: node.js express socket.io

完成Code School的node.js课程后,我按照this指南了解如何设置带有express 3的socket.io服务器,但是当我尝试连接到localhost:8080时,它给了我“无法获取/ ”。
我的防火墙设置为允许端口8080上的传入和传出请求,并且我安装了最新版本的express和socket.io。我的代码如下:

app.js

var express = require("express");
var socket = require("socket.io");

var app = express();
app.use(express.static(__dirname + "/public"));
var server = app.listen(8080);
var io = socket.listen(server);

的index.html

<!doctype html>
<html>
    <head>
        <script src="/socket.io/socket.io.js"></script>
        <script type="text/javascript">
            var server = io.connect("http://localhost:8080");
        </script>
    </head>
    <body>
        <p>Test</p>
    </body>
</html>

目录结构

C:\Users\Joseph\Desktop\test\node_modules
                            \public\index.html
                            \app.js

编辑:

这在app.js中也不起作用:

var http = require("http");
var express = require("express");
var socket = require("socket.io");

var app = express();
app.use(express.static(__dirname + "/public"));
var server = http.createServer(app);
server.listen(8080);
var io = socket.listen(server);

2 个答案:

答案 0 :(得分:1)

我发现我收到了错误,因为node不够智能,默认情况下从localhost:8080定位index.htm,因此我需要键入localhost:8080 / index.htm来访问该页面。

答案 1 :(得分:0)

那么如果这不适用于Windows,请尝试在app.js中执行此操作:

var express = require("express");
var socket = require("socket.io");
var path = require('path');
 // path is a built-in modules

var app = express();
app.use(express.static(path.join(__dirname, 'public')));
var server = app.listen(8080);
var io = socket.listen(server);