Zoltán Schmidt
Zoltán Schmidt

Reputation: 1345

Unable to attach any file to an HTML

Based on the tutorials I tried to set up a basic server in NodeJS via HapiJS.

The initialization looks like this:

    //globals
    mainAddr = "MoriMachine";
    mainPort = 3000;

    require('./backend/app.js')

This is the content of app.js:

    const Hapi = require('hapi');
    const server = new Hapi.Server();

    server.connection({host: mainAddr, port: mainPort });
    server.register(require('inert'), (err) => {
        if (err) { throw err; }
        server.route({
            method: 'GET',
            path: '/',
            handler: function (request, reply) {
                reply.file('./public/index/index.html');
            }
        });
    });

    server.start((err) => {
        if (err) { throw err; }
        console.log(`Server running at: ${server.info.uri}`);
    });

While index.html is similarly small:

            <!DOCTYPE html>
            <html>
                <head>
                    <script src="index.js"></script>
                </head>
                <body>
                <h1>HELLO WORLD!! -3-</h1>
                    <img src="test.jpg"></img>
                </body>
            </html>

In the project itself, there are init.js and three folders:

The problem is that whatever path I try, when I run the server, neither the JS or the picture are found.

What is the reason? An I missing to add some additional functionality?

Upvotes: 0

Views: 91

Answers (1)

SirGallifrey
SirGallifrey

Reputation: 46

The reason is that you only got one route that serves one specific file. When you access the route '/' your browser tries to access '/index.js' and '/test.jpg' and you are not responding to these routes.

One way to do is is to serve everything in your public directory, like this:

server.route({
    method: 'GET',
    path: '/{param*}',
    handler: {
        directory: {
            path: 'public'
        }
    }
});

Now your index.js is accessible trough /index/index.js and your image is accessible trough /index/test.jpg

so make these changes to your html

        <!DOCTYPE html>
        <html>
            <head>
                <script src="/index/index.js"></script>
            </head>
            <body>
            <h1>HELLO WORLD!! -3-</h1>
                <img src="/index/test.jpg"></img>
            </body>
        </html>

Note that in this way your index.html is also accessible trough /index/index.html

for more detaisl look at: http://hapijs.com/tutorials/serving-files?lang=en_US#directory-handler

Upvotes: 1

Related Questions