【问题标题】:hapi single page application using inert plugin doesn't serve up api route使用惰性插件的 hapi 单页应用程序不提供 api 路由
【发布时间】:2017-08-08 02:26:47
【问题描述】:

我正在尝试使用 hapi 和 inert 构建单页应用程序。

我的示例代码在这里:https://github.com/7seven7lst/hapi-inert-test

项目的基础是从nodejs hapi single page这里的答案构建的

基本上我想将静态文件和 api json 数据都发送到前端。我知道如何在快递中做到这一点,但还没有弄清楚如何使用 hapi。 delimma 是:如果我只使用 hapi,它不会提供静态文件,如果我使用 hapi+inert,它不会提供 api 路由。

解决方案????

【问题讨论】:

    标签: hapijs


    【解决方案1】:

    文档说路由处理程序从最具体到最不具体选择路由。因此,您可以使用 /api/v1/ 之类的东西预先修复您的 api 路由,然后不以 /api/v1/ 开头的所有其他内容都将被路由到由 inert 丢弃的静态文件。

    Hapi.js Routing Documentation:

    在确定对特定请求使用什么处理程序时,hapi 按从最具体到最不具体的顺序搜索路径。这意味着如果您有两条路线,一条带有路径 /filename.jpg 和第二条路线 /filename.{ext} 对 /filename.jpg 的请求将匹配第一条路线,而不是第二条路线。这也意味着路径为 /{files*} 的路由将是最后测试的路由,并且只有在所有其他路由都失败时才会匹配。

    'use strict'
    
    const Hapi= require('Hapi')
    
    // Config
    var config= {
        connection: {port: 3000, host: 'localhost'}
    }
    
    const server= new Hapi.Server()
    server.connection(config.connection)
    
    
    const plugins= [
        // https://github.com/hapijs/inert
        {   register: require('inert'), options: {} },
    ]
    
    function setupRoutes() {
    
        // Sample API Route
        server.route({
            method: 'GET',
            path: '/api/v1/Person/{name}',
            handler: function (req, reply) {
                reply('Hello, '+ encodeURIComponent(req.params.name)+ '!')
            }
        })
    
        // Web Server Route
        server.route({
            method: 'GET',
            path: '/{files*}',
            // https://github.com/hapijs/inert#the-directory-handler
            handler: {directory: {path: '../html_root', listing: false, index: true } }
        })
    }
    
    server.register(plugins, (err)=> {
        if (err) {throw err}
    
        // Initialize all routes
        setupRoutes()
    
        // Start the Server
        server.start((err)=> {
            if (err) {throw err}
            server.log('info', `Server running at: ${server.info.uri}`)
        })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 2019-09-03
      • 2019-03-05
      • 2015-03-17
      • 2014-01-21
      • 1970-01-01
      • 2015-12-08
      相关资源
      最近更新 更多