nodeJS在简单代码中获取错误

时间:2015-02-15 20:26:40

标签: javascript node.js

我是nodeJS的新手,在通过npm命令成功安装socket.io后,我创建简单的js作为此代码:

var app   = require('http').createServer(handler),
    io    = require('socket.io').listen(app),
    fs    = require('fs');

function handler( request, response ) {

  fs.readFileSync( __dirname + '/index.html', function( error, data ) {

    if( error ) throw error;
    response.writeHead(200);
    response.end( data );

  });
};

app.listen( 1377 )
io.sockets.on( 'connection', function( socket ) {
  socket.on( 'loginRequest', function( data ) {
    login( data );
  });
});

function login( data, socket) {
  return socket.emit('loginAnswer', true)
};

这个文件可以node application.js正确运行,没有任何问题,现在我创建简单的HTML代码:

<!DOCTYPE html>
  <html>
    <head>
        <script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<script>
  var socket = io('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>
    </head>
    <body>
      <form onsubmit='requestLogin()'>
        <input id='username' type='text'>
        <input id='password' type='password'>
        <input type='submit'>
      </form>
        </body>
  </html>

这个文件的名字是index.html,我正在使用xampp,两个文件都在htdocs root中,htdocs只有这个文件,现在我在浏览器中打开localhost:1337,我收到错误< / p>

将更改地址更改为localhost:1337后,我收到此错误:

Unable to connect
Firefox can't establish a connection to the server at localhost:1337.

1 个答案:

答案 0 :(得分:-1)

您使用fs.readFileSync,您应该使用fs.readFile, 还意识到你听1377端口,并尝试使用端口1337, 在index.html中将端口添加到套接字连接io('http://localhost:1377');