【问题标题】:Access static files using a relative path in hapi使用 hapi 中的相对路径访问静态文件
【发布时间】:2017-02-09 04:07:47
【问题描述】:

我已经通过http://hapijs.com/tutorials/serving-files

但这并没有帮助我。

我在项目根目录的静态目录中有一个文件a.js

我已将relativePath 配置为胶水配置为项目根目录中的inert 插件。

        plugins: {
            'vision': {},
            'inert': {
                routes: {
                    files: {
                        relativeTo: Path.join(__dirname, 'static')
                    }
                }
            },
            'visionary': {
                engines: {
             // other plugins

我的服务器路由如下:

{
    method: 'GET',
    path: '/a.js',
    handler: {
        file : 'a.js'
    }
}

但是当我尝试访问 http://localhost:3000/a.js 时,它会抛出 404 错误。

我错过了什么?

【问题讨论】:

    标签: node.js hapijs


    【解决方案1】:

    注册inert 插件是正确的方法,并允许您提供静态文件。

    您有多种选择来提供a.js 文件,例如使用通配符路由参数以动态方式提供各种 JS 文件。在 handler 中,您需要设置 JS 目录的路径,inert 将在该文件夹中搜索给定的 file

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

    您还可以指定到您的 JS 文件的静态路由并像这样提供它:

    server.route({  
      method: 'GET',
      path: '/mylocaljavascript.js',
      handler: function (request, reply) {
        // reply.file() expects the file path as parameter
        reply.file('../path/to/my/localjavascript.js')
      }
    })
    

    希望有帮助!

    如果您想了解有关提供静态文件的更多信息:https://futurestud.io/tutorials/hapi-how-to-serve-static-files-images-js-etc

    【讨论】:

      【解决方案2】:

      要为目录提供服务,您需要像这样设置路由:

      {
       path: '/{param*}',
       method: 'GET',
       config: {
        handler: {
         directory: {
           path: path.resolve('directory_path')
         }
        }
       }
      }
      

      要提供静态文件,您可以这样做:

      {
       path: '/your_path',
       method: 'GET',
       config: {
        handler: function(request, reply) {
         return reply.file('your_pfile_path');
        }
       }
      }
      

      不要忘记在您的 server.js 文件中添加惰性要求并进行注册。

      var Inert = require('inert');
      server.register(Inert, () => {});
      

      【讨论】:

        【解决方案3】:

        您需要将服务路由的代码更改为以下

        server.route({
            method: 'GET',
            path: '/a.js',
            handler: function (request, reply) {
                reply.file(a.js');
            }
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-18
          • 1970-01-01
          • 2014-07-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多