javascriptexpresswebsocketsocket.io

How do I make the http server, upgraded to websockets. listen to incoming requests so I can serve HTML page?


I was making a two-player game with websockets and express js and the folders are organized as follows.

.
├── public
│   ├── board.html
│   ├── board.js
│   ├── chess.css
│   └── util.js
├── server
│   ├── game.js
│   ├── node_modules
│   ├── package.json
│   ├── package-lock.json
│   └── server.js
└── todo.md

So, when I run node ./server/server.js. The server runs and listens on port 8000 but there is nothing showing. To make it show the main page(board.html). I have to go to localhost:8000/board.html and I don't want that.

My server.js looks like this.`

const http = require('http');
const express = require('express');
const cookieParser = require('cookie-parser');
const socketio = require('socket.io');
const { gameEnd, generateID } = require('./game.js');
let games = {};

const app = express();
app.use('/', express.static(`${__dirname}/../public/`));
app.use(cookieParser)

const server = http.createServer(app);
const io = socketio(server, {
    handlePreflightRequest: (req, res) => {
        const headers = {
            "Access-Control-Allow-Headers": "Content-Type, Authorization",
            "Access-Control-Allow-Origin": req.headers.origin, //or the specific origin you want to give access to,
            "Access-Control-Allow-Credentials": true
        };
        res.writeHead(200, headers);
        res.end();
    }
});
server.on('error', (err) => console.error(err));

server.listen(8000, () => {
    console.log('server is ready');
})

I want my app to show board.html straight away when I visit localhost:8000. What can I do to achieve that?

I have tried putting files outside of server folder and put them in root but to no avail.


Solution

  • Since you are serving static files using app.use(express.static(`${__dirname}/../public/`)); Express maps the url pathname to each file inside public folder.

    But since you want to make the board.html the home page, you have to define that. For that, you can add this line of code AFTER static file serving.

    Something like this:

    app.use(express.static(`${__dirname}/../public/`)); 
    
    app.get('/', (req, res) => {
        res.sendFile(`${__dirname}/../public/board.html`);
    });