Node.jsプロジェクトの構築方法を理解しようとしています。ノードによるルーティング
私はチャットアプリを作るために見つけたチュートリアルに従っています。
サーバー側とクライアント側の間のルーティングが機能していません。 あなたはなぜ私に説明することができますか、または、多分私はどのように一緒に動作する必要があるか理解するために良いリファレンスを与えることができますか?
これがサーバである:
var http = require('http');
const fs = require('fs');
var Router = require('router')
var router = Router();
router.get('/test', function (req, res) {
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.end('Hello World!');
})
var app = http.createServer(function (request, response) {
fs.readFile("public/client.html", 'utf-8', function (error, data) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.write(data);
response.end();
});
}).listen(1337);
var io = require('socket.io').listen(app);
io.sockets.on('connection', function(socket) {
socket.on('message_to_server', function(data) {
io.sockets.emit("message_to_client",{ message: data["message"] });
});
});
そして、これは、クライアントスクリプトとHTMLです:たぶん、明示またはHAPIを使用して
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socketio = io.connect("127.0.0.1:1337");
socketio.on("message_to_client", function(data) {
document.getElementById("chatlog").innerHTML = (document.getElementById("chatlog").innerHTML + "<hr/>" + data['message']);
});
var request = $.ajax({
url: "/test",
type: "GET"
});
request.done(function(msg) {
console.log(1111);
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
function sendMessage() {
var msg = document.getElementById("message_input").value;
socketio.emit("message_to_server", { message : msg});
window.scrollTo(0,document.body.scrollHeight);
}
</script>
</head>
<body>
<div id="wholeChat">
<div id="chatlog"></div>
<div>
<input type="text" id="message_input"/>
<button onclick="sendMessage()">send</button>
</div>
</div>
</body>
</html>
は物事がよりシンプルになりますが、その後私はできませんfs
モジュールでここでやっているように、ビューをロードするにはどうすればよいか理解してください。
ありがとうございます!私はあなたがそのようindex.hmml送信しようとしている理由を知らない
「動作していない」ということについていくつかの詳細を教えてください。間違いましたか?明示的なエラーがなくても表示されないことはありますか? –
あなたのルータはあなたのhttpサーバに全く接続しておらず、何もしていません。あなたがそのコードをどこから入手したかはわかりません。 https://www.npmjs.com/package/routerの例に従えば、ルータがhttpサーバに接続されている部分が見つからないことがわかります。 – jfriend00