如何将javascript包含到我的Express.js应用程序,也使用socket io?



这是一个倒计时项目,时间同步我使用https://www.npmjs.com/package/timesync

server.js

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
var timesyncServer = require('timesync/server');
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.get('/admin', (req, res) => {
res.sendFile(__dirname + '/admin.html');
});
io.on('connection', (socket) => {
console.log('success-connection')
socket.on('chat message', msg => {
io.emit('chat message', msg);
});  
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
});
// handle timesync requests
app.use('/timesync', timesyncServer.requestHandler);

我尝试了一些方法,但没有工作。
我得到了这个错误消息:
GET http://localhost:3000/script.js net::ERR_ABORTED 404 (Not Found)

这是我的项目:File-strucure

您正在尝试发送静态文件。res.sendFile(__dirname + '/index.html');。您需要启用在express应用程序中使用静态文件。将所有静态文件(html, css,图像,视频)放在一个文件夹中。命名为"static"。然后将这个中间件添加到你的应用程序

app.use("/static", express.static('./static/')); 

这应该足以提供静态文件。

相关内容