我想在Web服务器上使用套接字io。当我在本地主机上工作时,一切正常。我在plesk面板上安装了文件。节点模块安装成功。当我调用index.html时,出现错误http://example.com:3000/socket.io/socket.io.js。我的错误在哪里?
index.html
<!DOCTYPE html>
<html ng-app="socket" ng-controller="homeController">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="http://example.com:3000/socket.io/socket.io.js"></script>
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>id</th>
<th>Status</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="i in results">
<td>{{$index}}</td>
<td>{{i.status}}</td>
<td>{{i.category}}</td>
</tr>
</tbody>
</table>
</div>
</body>
<script>
var app = angular.module('socket', []);
app.controller('homeController', function ($scope) {
var socket = io.connect('http://example.com:3000');
socket.on('connected', function (data) {
socket.emit('ready for data', {});
});
socket.on('update', function (data) {
$scope.results = data;
if (!$scope.$$phase) $scope.$apply();
});
});
</script>
</html>
index.js
const Express = require('express');
const Request = require('request');
const http = require('http');
const db = require('./lib/database');
const app = Express();
const server = http.createServer(app);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.emit('connected', { connected: true });
socket.on('ready for data', function (data) {
db.on('notification', function(title) {
const sql = "select * from public.test";
db.query(sql, (err, result) => {
if (err) res.status(err.code).json({code: err.code, message: err.message}).end();
socket.emit('update', result.rows);
})
});
});
});
server.listen(3000);
答案 0 :(得分:0)
1- express.static
如果要提供JavaScript,CSS,Image等静态文件,则可以使用express.static内置的中间件功能。
函数签名为:
express.static(root, [options])
root参数指定用于从其提供静态资产的根目录。有关options参数的更多信息,请参见express.static。
例如,使用以下代码在名为public的目录中提供图像,CSS文件和JavaScript文件:
app.use(express.static('public'))
现在,您可以加载公共目录中的文件:
http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
2- CDN 或者,您可以将CDN用于socket.io.js或其他库,例如jquery,bootstrap等。
您可以从这里socket.io cdn
获取CDN