Mann
Mann

Reputation: 606

not loading jquery files in nodejs with hapi

I 've tried both the code (commented and uncommented) in the commented code it shows an error reply.file is not a fumction . In uncommented code it shows error unknown handler file I 've also included inert.

      server.route({    // Other assets If you have
        method: 'GET',
        path: '/public/js/{filename}',
        handler: {
       file: function (request) {
           return  './public/js/'+request.params.filename;
       }
//        try{
//            console.log(request.params);
//            reply.file( './public/js/'+request.params.filename);
//        }
//        catch(e){
//             console.log(e);
//            reply.file( './public/js/'+request.params.filename);
//        }
       }
});

Upvotes: 2

Views: 366

Answers (2)

aifarfa
aifarfa

Reputation: 3939

serving static files requires inert module

Updated


server.js

'use strict';

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

// config
server.connection({
    port: 3000
});

// register routes
server.register(Inert, (err) => {
    if (err) {
        throw err;
    }

    // default html
    server.route({
        method: 'GET',
        path: '/',
        handler: function (request, reply) {
            reply.file('./public/index.html');
        }
    });

    // default /js directory
    server.route({
        method: 'GET',
        path: '/js/{params*}',
        handler: {
            directory: {
                path: './public/js',
                listing: false
            }
        }
    });
});

// run
server.start(() => {
    console.log('Server running at:', server.info.uri);
});

public/index.html

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Hapi demo: serving static files</title>
    <script type="text/javascript" src="js/foo.js"></script>
</head>

<body>
    <h2>see console output.</h2>
</body>

</html>

public/js/foo.js

'use strict';

(function () {
    console.log('foo.js has been loaded');
})();

see: http://hapijs.com/tutorials/serving-files#relative-paths

Upvotes: 2

user3510665
user3510665

Reputation: 218

see: http://hapijs.com/tutorials/serving-files#relative-paths use inert module

server.register(Inert, function () {
  server.route( {
    method: 'GET',
    path: '/{param*}',
    handler: {
      directory: { path: Path.normalize(__dirname + '/') }
    }
  });

You can also try

server.register(Inert, () =>{
    server.route( {
        method: 'GET',
        path: '/public/js/{filename}',
        handler: {
            file: function (request) {
                return __dirname+'/public/js/'+request.params.filename;
            }
        }
    });
});

Upvotes: 1

Related Questions