node.js - hapi中使用相对路径访问静态文件

标签 node.js hapi.js

我已经浏览过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 错误。

我错过了什么?

最佳答案

注册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

关于node.js - hapi中使用相对路径访问静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33462130/

相关文章:

node.js - 如何在 mocha 的 mocha.opts 文件中添加 chaijs 的断言?

mysql - 多个控制字段在 Node.js 应用程序中不起作用

node.js - API 字符串未通过 Express 中的 console.log 传递

javascript - Hapi js重定向到带有附加请求数据的另一条路由

django - 客户端错误: bad object in message: bson length doesn't match what we found

node.js - Model.find({_id :req. body.id}) 找到该对象,但 Model.updateOne({_id :req. body.id},{//update}) 未找到该对象

testing - 在 Hapi.js 中调用 server.inject() POST 请求不调用处理程序

javascript - 使用 gulp 完成测试后,Hapi 注入(inject)不会退出到命令行

javascript - 在 hapi.js 中,身份验证方案和策略有什么区别?

javascript - 无效的承载访问 token