简体   繁体   中英

How to make Socket.IO serveClient option work?

I'd like to use client distrubuted with the socket.io package in client-side scripts.

This is what I did:

const IOserver = io.listen(server, { serveClient: true, path: "/socket.io.client.js" });

But when I try to access socket.io client on that path http://localhost:1337/socket.io.client.js I get a 404 error.

How to properly set up socket.io to serve client side JavaSript file?

I think you are confusing what the path properties does. The path is the endpoint it should use to connect to your websocket server.

You need to manage the installation of the frontend js client manually. It does not get fed in from your server.

I just met the problem.

If you want the serverClient option to work, you need to do as follows:

http version

// app.js file

const server = require('http').createServer((req, res) => {
  fs.readFile(__dirname + '/index.html',
  (err, data) => {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
});
const io = require('socket.io')(server, { serveClient: true });

server.listen(1234, () => {
  console.log('Server listening at http://localhost:1234.');
})

Or express version:

const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server, { serveClient: true });

server.listen(1234, () => {
  console.log('Server listening at http://localhost:1234.');
})

And then, you can obtain the socket.io.js file by link http://localhost:1234/socket.io/socket.io.js , or socket.io.js.map file by link http://localhost:1234/socket.io/socket.io.js.map .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM