2013-10-10 126 views
0

我正在使用Node.js並表示製作網絡聊天應用程序。我有一個關於路由的問題。定義節點js的模式路由

我的路線是:

app.get("/", function(req, res) { 
    res.sendfile(__dirname + "/index.html"); 
}); 

而且據我所知,這意味着所有客戶端應該去http://www.example.com/index.html頁面訪問聊天。 (也許,不知道)

是否有可能有一個模式URL像這樣:

app.get("/*", function(req, res) { 
    res.sendfile(__dirname + "/*"); 
}); 

,使任何用戶都可以訪問任何URL
聊天簡而言之:喜歡的東西Facebook聊天。可在所有頁面訪問。

在此先感謝

+0

對於你的例子:'app.use(express.static(__ dirname));'。但是,我認爲你誤解了Facebook的聊天工作。您需要查看客戶端通信,如[Ajax](https://developer.mozilla.org/en-US/docs/AJAX)和[WebSockets](https://developer.mozilla.org/en-US /文檔/的WebSockets)。而且,這些可以從您選擇實施它們的任何頁面使用。 –

+1

對於Node.js使用WebSocket等,你可以試試[socket.io](http://socket.io/)。 [實施例](https://github.com/LearnBoost/socket.io/tree/0.9.15/examples/chat)。 –

+0

我使用的是socket.io,但我在路由時遇到了問題。我的聊天應用程序即將完成。但只能在/index.html中訪問。因爲我的路線。 – Pars

回答

3

是否有可能有一個模式URL是這樣的:

是的,Express支持你列出的路線。該文件將其稱爲「未命名的通配符」。

// GET /foo  -> (200) "foo" 
// GET /baz/qux -> (200) "baz/qux" 

app.get('/*', function (req, res) { 
    res.send(req.params[0]); 
}); 

雖然,你比如,快遞/連接中包含爲URL路徑合併到基本目錄中的服務文件static() middleware

app.use(express.static(__dirname)); 

東西像Facebook聊天。可在所有頁面訪問。

這不一定與路由有很大的關係。您的應用程序可能需要一個路線來收集聯繫人列表或其他持久數據,但實際的「chat」將單獨管理。

一般情況下,這將取決於包括在每個頁面的公共內容 - 或許通過「佈局」或「繼承」如果你使用的意見/模板 - 顯示用於輸入消息的形式以及顯示聊天記錄的區域。此外,聊天中的相當數量的「工作」將不得不在客戶端完成。

一個簡單的例子是充當多個URL相同的文件:

var app = require('express')(); 
var server = require('http').createServer(app); 
var io = require('socket.io').listen(server); 

app.get('/*', function (req, res) { 
    res.sendfile(__dirname + '/chat.html'); 
}); 

var chat = io 
    .of('/chat') // namespace 
    .on('connection', function (socket) { 
     socket.on('message', function (data) { 
      chat.emit('message', data); 
     }); 
    }); 

server.listen(3000); 

而且,在該文件中:

<div id="chat-log"></div> 
<form id="chat-send"> 
    <input name="message"> 
    <input type="submit" value="Send"> 
</form> 

<script src="/socket.io/socket.io.js"></script> 
<script> 
    var chatForm = document.getElementById('chat-send'); 
    var chatLog = document.getElementById('chat-log'); 

    var chatSocket = io.connect('/chat'); 

    chatSocket.on('message', function (data) { 
     chatLog 
      .appendChild(document.createElement('div')) 
      .appendChild(document.createTextNode(data.text)); 
    }); 

    chatForm.onsubmit = function() { 
     chatSocket.emit('message', { 
      text: chatForm.message.value 
     }); 

     chatForm.message.value = ''; 
     chatForm.message.focus(); 
     return false; 
    }; 
</script> 

然後,從任何地址(GET /GET /fooGET /bar/baz/qux) ,你可以訪問聊天。

+0

非常感謝這麼好的回覆。我已經在客戶端和服務器端完全像facebook一樣聊天。但我的問題是關於在所有網址中訪問它。我將爲此使用PHP Laravel。它支持佈局,並且所有的URL都首先引用index.php然後渲染。我想知道如果我定義了一個/index.php,它將在我所有的頁面中工作,同時我用laravel開發了我的網站......! – Pars

0

你可能會想使用URL PARAM這樣的:

app.get("/:chatter",function(req,res){ 
    console.log("the chatter is",req.param('chatter')); 
    res.sendfile(__dirname + "/index.html"); 
    ... 
});