关于使用在node中使用jquery的一点小问题,求解
发布于 10 年前 作者 zycralf 4339 次浏览 最后一次编辑是 8 年前

各位大神,小弟初学node,遇到一个小问题,度娘问不出答案,只好求教。跪谢。。。 用socket.io实现ping和pong对话时,引用了jquery。 代码如下: 服务器端:

var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
  fs.readFile('./index.html', function(error, data) {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end(data, 'utf-8');
  });
}).listen(3000, "127.0.0.1");
console.log('Server running at http://127.0.0.1:3000/');

var io = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  socket.on('ping', function (data) {
    console.log('Received PING. Sending PONG..');
    socket.emit('pong', { text: 'PONG' });
  });
  socket.on('pong', function (data) {
    console.log('Received PONG response. PONG!');
  });
  setInterval(function() {
    console.log('Sending PING to client..');
    socket.emit('ping', { text: 'PING' });
  }, 10000);
});

客户端:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Socket.IO Example</title>
  </head>
  <body>
    <h1>Socket.IO Example</h1>
    <button id="ping">Send PING to server</button>
    <script src="/jquery-1.9.1.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io.connect('http://127.0.0.1:3000');
      socket.on('ping', function (data) {
        console.log('Received PING. Sending PONG..');
        socket.emit('pong', { text: 'PONG' });
      });
      socket.on('pong', function (data) {
        console.log('Received PONG response. PONG!');
      });
      $('#ping').click(function() {
        console.log('Sending PING to server..')
        socket.emit('ping', { text: 'PING' });
      });
    </script>

  </body>
</html>

我的jquery-1.9.1.min.js文件就放在上面两个文件同一目录下,可是运行的时候ie却报出如下错误: 网页错误详细信息

消息: 语法错误 
行: 1
字符: 1
代码: 0
URI: http://localhost:3000/jquery-1.9.1.min.js

代码里的引用确实是 <script src="/jquery-1.9.1.min.js"></script> 啊,jquery-1.9.1.min.js文件也存在啊,到底怎么回事呢,我折腾了一晚上了,崩溃边缘,求各位大神帮帮小弟。先跪谢了。 另求解: URI: localhost:3000/jquery-1.9.1.min.js里的localhost:3000/是指的哪个目录。

2 回复

楼主没个请求都返回 HTML, 结果当然出错了 localhost:3000/ 没有对应目录, Node 脚本中的目录是一般脚本文件所在的目录

谢谢解答,小弟再研究研究

回到顶部