Jacob
Jacob

Reputation: 659

css/js file reference error while rendering a page using Node.js

I'm trying to load a page using Node.js as a server.

I'm trying to crate an API that loads a different page accordingly with the user input.

I'm using the following code:

app.get('/apitest/:id', function(request, response) {

    const requestId = request.params.id;    

    if(requestId == 1){
        response.render('pages/index2');
    } else if(requestId == 2){
        response.render('pages/index3');
    } else{
        response.render('pages/404');
    }
});

The problem is that the js and css files included into the loaded pages cannot be found. The reason is that the server looks for them at the wrong path which is the following one:

http://localhost:5000/apitest/js/three/examples/js/renderers/CanvasRenderer.js

But all the js/css files are in the folder public/js and public/css (classic server Node.js path).

So if I just load the page using

app.get('/', function(request, response) {  
    response.render('pages/index');
});

everything works perfectly and the scripts are perfectly loaded, but if I try to use the the first snippet of code the server cannot find them anymore.

How can I solve this problem? Thanks.

Upvotes: 0

Views: 95

Answers (1)

taha
taha

Reputation: 1017

specify a mount path :

// path should be required
`app.use('/apitest/:id', express.static(path.join(__dirname, 'public')))`

Upvotes: 1

Related Questions