簡體   English   中英

在Node.js中處理.js和.css

[英]Handling .js and .css in Node.js

我正在嘗試使用node.js和jQuery創建一個簡單的聊天應用程序,但是我的控制台出現一個錯誤,提示“未定義$”。 我正在跟蹤一個教程,其中authr使用jquery沒有問題。

我的chat.js(服務器):

var http = require('http'),
sys = require('sys'),
fs = require('fs'),
ws = require('./ws.js');


var clients = [];
http.createServer(function(req,res){
    res.writeHead(200,{
        'Content-Type': 'text/html'
    });
    var rs = fs.createReadStream(__dirname + '/test.html');
    sys.pump(rs, res);
}).listen(4000);

    ws.createServer(function(websocket){

    websocket.on('connect', function(resource){
        clients.push(websockets);
        websocket.write('Welcome');
    });

    websocket.on('data', function(data){
        clients.forEach(function(client){
            client.write(data);
        });
    });

    websocket.on('close',function(){
        var pos = clients.indexOf(websocket);
        if(pos >= 0){
            clients.splice(pos, 1);
        }
    });
}).listen(8081);

test.html(客戶端):

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(e) {
        ws = new WebSocket("ws://localhost:8080");
        ws.onmessage = function(event){
            var data = data.replace(/&/g, "&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");

            $('#log ul').append('<li>' + data + '</li>');
            }
    });
</script>
</head>

<body>
<div id="log"><ul></ul></div>
  <div id="console">
  <input type="text" id="entry"/>
  </div>
  </div>

</body>
</html>

在刪除所有.css和其他.js src之前,我遇到了錯誤,因此,我很確定問題出在服務器中的“ Content-Type”代碼上。

在服務器端,您使用的代碼很舊。 sys.pump已被棄用至少一年以上。

我建議您閱讀socket.io中的示例。 在示例中也有一個聊天服務器

誰在提供您的靜態文件? 從您擁有的代碼看來,您正在提供的唯一靜態文件是HTML頁面。

您需要添加一些代碼來處理特定位置的所有靜態文件。 基本上,您需要處理自己內部的所有靜態文件

http.createServer(function() {...}) 

請參閱: http//www.sitepoint.com/serving-static-files-with-node-js/

我懷疑問題是您沒有從服務器提供jquery-1.7.2.min.js,因此網頁未加載jquery,因此沒有$。 首先,嘗試引用托管的jquery,看看是否可以解決您的問題。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

盡管與您的問題並不完全相關,但是如果您正在構建一個公共網站,則通常最好參考托管的jQuery(和其他庫),因為您的用戶可能已經擁有本地緩存​​的副本(這要歸功於其他網站)一樣的東西)。 有關此問題的合理說明,請參見http://encosia.com/3-reasons-why-you-should-let-google-host-jquery-for-you/

通常,盡管如此,您將要提供一些靜態文件:您自己的css和js,圖像等。 大量 帖子描述了如何使用node進行此操作,但是您可能希望查看如下專用模塊: https : //github.com/cloudhead/node-static

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM