当我的HTML之外有这个JS + jQuery代码段时,该函数将拒绝触发。我弄清楚了原因,这是因为它拒绝加载。
我正在使用带有ExpressJS和Socket.IO的nodeJS。我尝试搜索其他问题/场景,他们建议在js上添加斜杠或缺少类型,但我已经尝试过。
编辑:我认为我没有正确地将CSS或JS发送到Node / Express服务器?我在最后添加了Node / Express JS。
控制台日志
The resource from “http://localhost:3000/styles.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
localhost:3000
The resource from “http://localhost:3000/client.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
localhost:3000
The resource from “http://localhost:3000/client.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).
localhost:3000
Loading failed for the <script> with source “http://localhost:3000/client.js”.
client.JS
let socket;
$(document).ready(onLoad());
function onLoad() {
console.log("initating js");
socket = io();
$('form').submit(function(e){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
}
这是我的HTML,当我将以上内容放回到client.js部分中时,它就可以正常工作。我尝试在client.JS之前/之后移动Socket.IO脚本,它没有任何效果。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Socket.IO chat</title>
<link rel="stylesheet" type="text/css" href="/styles.css">
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<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 src="/client.js" type="text/javascript"></script>
</body>
</html>
这里是Node / Express JS
var app = require('express')(); //init app to be a func handler, we can supply this to a http server
var http = require('http').createServer(app); // supply app to a http server
var io = require('socket.io')(http); // add socket.io object
app.get('/', function(req, res){ // defines a route handler
res.sendFile(__dirname + '/index.html');
});
// use socket.io obj and listen on connection events for an inc socket param
io.on('connection', function(socket){
console.log('a user connected'); // show status for connectors
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
socket.on('disconnect', function(){
console.log('user disconnected'); // show status for disconnectors
});
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3000, function(){ // tell the server 'http' to listen on port 3000
console.log('listening on *:3000');
});
将client.js
放在根目录下的目录中,例如{root_dir_name}/public
。
然后将app.use(express.static('public'))
添加到您的node.js文件。