我使用 NodeJS 来提供一些文件,但页面一直在加载。
这是我的 index.js
文件。
const express = require("express");
const path = require("path");
const http = require("http");
const socketio = require("socket.io");
const app = express();
const PORT = process.env.PORT || 3000;
const server = http.createServer(app);
const io = socketio(server);
app.use(express.static(path.join(__dirname, "../public")));
server.listen(PORT, () => {
console.log("server listening to port: " + PORT);
});
这是我的 public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="icon" href="/favicon.ico">
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<div id="media-video">
<video id="media-camera" autoplay="autoplay" playsinline>
</video>
<video id="media-remote-video" autoplay="autoplay" playsinline>
</video>
<video id="media-screen-capture" autoplay="autoplay" playsinline>
</video>
<select name="video" id="media-video-devices">
<option value="None">None</option>
</select>
<select name="audio" id="media-audio-devices">
<option value="None">None</option>
</select>
<button id="start-media-stream">Start Stream</button>
<button id="end-media-stream">End Stream</button>
<button id="start-media-screen-capture">Capture Screen</button>
<button id="end-media-screen-capture">End screen capture</button>
</div>
<script src="/socket.io/socket.io.js"></script>
<script src="/js/index.js"></script>
</body>
</html>
页面加载完美,包括所有 JS 和 css 文件,但仍然 locahost:3000 继续加载。
答案 0 :(得分:0)
Express 在创建套接字服务器时创建了一个 web 服务器,它们都从同一个端口提供服务,在本例中为 3000。要连接到 websocket,您需要使用 socket.io 连接到 "ws://localhost: 3000" 而不是您可能发出的任何 http 请求。
答案 1 :(得分:0)
页面“挂起”,因为您没有向用户发送响应。该代码只是为中间件 express 静态文件提供服务,但是您没有处理请求/响应周期...
这是您可以执行的操作的示例:
// require http native node api...
var http = require('http');
// initialize express...here the server is not listening
// your files are not served yet...
var app = require('express')();
// this is the middleware that serves your static files
// the css and js come from this...
app.use(express.static(path.join(__dirname, "../public")));
// now you create the server using the HTTP module
// passing express as function and the PORT you have set...
// this is listening, not handling your request/response cycle...
http.createServer(app).listen(PORT);
// this is an example of how you end a request response cycle
// by sending a file back, it could be other things...
app.get('/', function(req, res) {
res.sendFile("index.js");
});