Home > Blockchain >  CSS loads but doesn't do anything
CSS loads but doesn't do anything

Time:12-31

I'm trying to make a basic multiplayer game with Socket.IO, p5.js and NodeJS, hosting it on Replit.

I have a basic httpServer with socket.io, and it serves the HTML, CSS and JavaScript files fine. But when I put the <link> tag in the HTML to load the CSS, the CSS loads fine (I can see it in the Sources tab in the Chrome DevTools) but it doesn't actually apply to the HTML.

The code is here, but I'll put it here as well.

index.js The main NodeJS file

const { readFileSync } = require('fs');
const { createServer } = require('http');
const { Server } = require('socket.io');

const httpServer = createServer((req, res) => {
  const r = /^\/?(index\.(html|css|js))?$/i;

  if (!r.test(req.url))
  {
    res.writeHead(404);
    res.end('Not found');

    return;
  }

  const m = req.url.match(r);

  // reload the file every time
  const content = readFileSync(__dirname   '/public/'   (m[1] || 'index.html'));
  const length = Buffer.byteLength(content);

  res.writeHead(200, {
    'Content-Type': 'text/html',
    'Content-Length': length,
  });
  res.end(content);
});

const io = new Server(httpServer, {
  // Socket.IO options
});

let players = {};

io.on('connection', (socket) => {
  players[socket.id] = {
    id: socket.id,
    x: 0,
    y: 0
  };

  socket.on('disconnect', (reason) => {
    delete players[socket.id];
  });
});

io.on('data', data => {
  players[data.id].x  = data.x;
  players[data.id].y  = data.y;
});

setInterval(() => {
  io.sockets.emit('data', players);
}, 1000 / 60);

httpServer.listen(6001);

public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Multiplayer Online IO Game 2</title>

  <link rel="stylesheet" href="index.css">

  <script src="/socket.io/socket.io.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.min.js" integrity="sha512-N4kV7GkNv7QR7RX9YF/olywyIgIwNvfEe2nZtfyj73HdjCUkAfOBDbcuJ/cTaN04JKRnw1YG1wnUyNKMsNgg3g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <script src="/index.js" defer></script>
</head>
<body>
  
</body>
</html>

public/index.css

body
{
  margin: 0px;

  overflow: hidden;
}

canvas
{
  display: none;
}

The canvas' display: none was to see if the CSS actually did anything, but it doesn't.


public/index.js The client JavaScript

let ID = null;
let players = {};

const socket = io({
  // Socket.IO options
});

socket.on('connect', () => {
  ID = socket.id;
});

socket.on('connect_error', (err) => {
  alert(`There was an error connecting to the WebSocket server:\n${err.message}`);
});

socket.on('data', (data) => {
  players = data;
});

function setup()
{
  createCanvas(windowWidth, windowHeight);
}

function draw()
{
  background(255);

  fill(0);

  for (const id of Object.keys(players))
  {
    const player = players[id];

    circle(player.x, player.y, 10);
  }

}

CodePudding user response:

Your server is using the content type text/html for all responses regardless of the type of file being returned. Some web browsers are strict about content-types and will not process a stylesheet if it has the wrong content type. Here's a example fix:

const httpServer = createServer((req, res) => {
  const r = /^\/?(index\.(html|css|js))?$/i;

  if (!r.test(req.url))
  {
    res.writeHead(404);
    res.end('Not found');

    return;
  }

  const m = req.url.match(r);

  // reload the file every time
  const content = readFileSync(__dirname   '/public/'   (m[1] || 'index.html'));
  const length = Buffer.byteLength(content);

  res.writeHead(200, {
    // Determine the content type based on the file extension
    'Content-Type': m[2] ? getContentType(m[2]) : 'text/html',
    'Content-Length': length,
  });
  res.end(content);
});

function getContentType(ext) {
  switch (ext.toLowerCase()) {
    case 'html':
      return 'text/html';
    case 'css':
      return 'text/css';
    case 'js':
      return 'text/javascript';
    default:
      return 'application/octet-stream';
  }
}

You might want to consider using a more full-featured HTTP server such as express instead of rolling your own.

  • Related