开发Zoom克隆项目时遭遇PeerJS接口404(Not Found)错误的技术求助
Hey there, the 404 error you're hitting is a super common small oversight—you've set up the ExpressPeerServer in your backend, but haven't mounted it to your Express app's route yet. The client is trying to reach /peerjs/id to fetch a peer ID, but your server isn't configured to handle that path right now.
Here's the simple fix:
In your server-side code, add this line right after your app.use(express.static('public')); statement:
app.use('/peerjs', peerServer);
This tells Express to route all requests starting with /peerjs directly to your PeerJS server, which will handle the /id endpoint your client is requesting.
Updated Server Code:
const express = require('express') const app = express(); const server = require('http').Server(app); const io = require('socket.io')(server); const { v4: uuidv4 } = require('uuid'); const { ExpressPeerServer } = require('peer'); const peerServer = ExpressPeerServer(server, { debug: true }); app.set('view engine', 'ejs'); app.use(express.static('public')); // Mount the PeerJS server to the /peerjs route (this fixes the 404!) app.use('/peerjs', peerServer); app.get('/', (req, res) => { res.redirect(`/${uuidv4()}`); }) app.get('/:room', (req, res) => { res.render('room', { roomId: req.params.room }); }) io.on('connection', socket => { socket.on('join-room', (roomId, userId) => { socket.join(roomId); // Quick tweak: `broadcast` is redundant here—socket.to(roomId) already sends to other users in the room socket.to(roomId).emit('user-connected', userId); }) }) server.listen(3030);
Quick Client Code Validation:
Your client's Peer configuration is already correct:
var peer = new Peer(undefined, { path: '/peerjs', host: '/', port: '3030' });
Now that we've mounted the PeerJS server to /peerjs on port 3030, this will correctly reach the server instead of hitting a 404.
Just restart your server after adding that line, and the error should vanish immediately.
内容的提问来源于stack exchange,提问作者smrtdvlpr

