Hapi.js views not seeing local scripts

2019-05-22 18:28发布

问题:

I'm currently working on an app with a server that uses Hapi, and I am running into a problem whenever I try to load a .jade file. Here is the current code for my index.js file:

var Hapi = require('hapi');

var internals = {};

internals.main = function() {
  var options = {
    views: {
      engines: { jade: 'jade' },
      path: '../app',
      compileOptions: {
        pretty: true
      }
    }
  };

  this._server = new Hapi.createServer('localhost', 8000, options);

  this._server.route({
    method: 'GET',
    path: '/',
    handler: function(request, reply) {
      reply.view('index')
    }
  });
  // Start server.
  this._server.start()
};

internals.main();

The file has a series of local scripts and CSS files that are in the app directory, but when the page index.jade is loaded, it does not see those local files. Is there something I need to add/modify in my options, or is this location of local scripts and style files a problem with jade compilation using Hapi?

回答1:

I was looking for a similar solution, while trying to setup a single page application with angular.js and hapi.js

I have found that adding the configuration below to your server routes will help to make CSS, JS, ... files in '/public' directory visible to the application.

server.route({
    method: "GET",
    path: "/public/{path*}",
    handler: {
        directory: {
            path: "./public",
            listing: false,
            index: false
        }
    }
});

Hope it helps.