不使用hapi在nodejs中加载jquery文件

时间:2016-02-08 05:48:53

标签: node.js hapijs

我已经在注释代码中尝试了代码(注释和未注释),它显示错误reply.file不是一个功能。在未注释的代码中,它显示错误未知的处理程序文件 我还包括惰性。

      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);
//        }
       }
});

2 个答案:

答案 0 :(得分:2)

提供静态文件需要inert模块

更新

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);
});

公共/ 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>

公共/ JS / foo.js

'use strict';

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

请参阅:http://hapijs.com/tutorials/serving-files#relative-paths

答案 1 :(得分:1)

见:http://hapijs.com/tutorials/serving-files#relative-paths 使用inert模块

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

您也可以尝试

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