当我运行server.js时,我在我的控制台中得到此错误GET http://localhost:8080/style.css // 获取http://localhost:8080/style.css
我的目录结构如下: 我的目录结构如下:
|-- public
|-- style.css
|-- client.js
|-- server.js
|-- package.json
server.js
var express = require('express');
var app = express();
var http = require('http');
var port = process.env.PORT || 8080;
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.get('/', function (req, res) {
res.render('index.html');
});
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('chat-msg', function (message) {
console.log('message' + message.text);
});
});
server.listen(port);
HTML
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css" type="text/css"/>
<title>Socket.IO chat</title>
</head>
<body>
<h1>HELLO COMMUNICATION</h1>
<section id="chat">
<ul id="messages"></ul>
<form action="">
<input id="m"/><button>Send</button>
</form>
</section>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="client.js"></script>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('message',function(message){
console.log('le serveur dit'+message);
})
</script>
</body>
</html>
client.js
var socket = io();
$('form').submit(function(e){
e.preventDefault(); // On évite le recharchement de la page lors de la validation du formulaire
var message={
text : $('#m').val()
}
socket.emit('chat-msg',message); // On émet l'événement avec le message associé
$('#m').val(''); //on vide le champ text
if(message.text.trim().length !== 0){//gestion message vide
socket.emit('chat-msg',message);
}
$('#chat input').focus();
});
答案 0 :(得分:0)
你是如何运行server.js的?
如果您在public
目录中并运行node server.js
,我认为该路径无法正常运行
app.use(express.static(__dirname + '/public'));
因为它会查找不存在的public
目录