Search code examples
javascriptnode.jsserverxmlhttprequest

Serve static files for an URL with dynamic params in node js without any library or framework


I have a little problem here. I want to serve one static file for "/user/:id" URL with a simple node server. How is this possible? Here is my request in client side:

document.location.href = `http://localhost:8080/user/${x}`;

And this is my request handler:

var routeHandler;
if (req.method === 'GET') {
        switch (req.url) {
            case '/user/:id':
                routeHandler = userProvider;
                break;
        }
}

function userProvider(req, res) {
        req.url = 'index.html';
        staticFileHandler(req, res);
}

function staticFileHandler(req, res) {
        fs.readFile('client/' + req.url, function (err, data) {
            if (err) {
                res.writeHead(500);
                res.write(err.name);
                res.end();
            }
            res.writeHead(200);
            res.write(data);
            res.end();
        });
    }

Is there any way to handle this request only with nodejs not using express or any other libraries?


Solution

  • Since req.url isn't going to be an exact match for case '/user/:id':, don't use a switch.

    Use an if test using a regular expression instead.

    if ( req.url.match(/^\/user\/\d+/);