nodejs hapi单页

Amí*_*les 11 routing node.js angularjs hapijs

我有一个应用程序站点(NodeJS),我想从Express迁移到Hapi,我通常做的是提供静态文件并将其他所有内容路由到包含angularjs应用程序和角度路由配置的单个页面.

// Express routing, first the static files
app.use( express.static(__dirname + '/public') );

// Second the api routes
app.get('/api', function(req, res){
    res.send( {api: 'response' } )
});

// Finally everything else maps to the single page app:
app.get('*', function(req, res){
    res.sendfile('./public/html/controllers.index.html')
});
Run Code Online (Sandbox Code Playgroud)

在HapiJS中,我不知道如何复制相同的代码(不使用express.static中间件),因为:

Hapi = require('hapi');
var server =  new Hapi.Server('localhost', 84);

server.route({
    method: 'GET',
    path: '/{p*}',
    handler: function (request, reply) {
        reply.file('public/html/index.html');
    }
});
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,每个请求都会被映射到我的单页('public/html/index.html'),但是如果我这样做,那么js,css,jpg和文件将被映射到同一个文件而不是脚本,样式和图像(对'/images/bg.png'的请求将下载单页而不是图像文件).

我知道如果我将路径'/'设置为单页,然后'{p*}'设置为'{directory:{path:'/ public'}}'那么我将拥有我需要的行为,但是如果一些用户复制并粘贴一个特定网址(比如'/ account/login')然后点击回车,那么该路由将被映射到HapiJS并且响应将是'Not Found(404)',角度路由将永远无法回应.

有人知道如何解决这个问题吗?

问题的关键部分是:

  • 仅使用HapiJS(无快递或其他中间件)
  • 不要路由每个角度路由(只是路由其他一些尚未路由到单页子角度的路径可以处理路由)

Jan*_*_dh 7

不确定这是否会帮助你,但你的起始代码对于Hapi.js来说有点"奇怪".这是我用来设置一个简单的hapi.js SPA.

如果您希望使用特定的URL(如帐户/登录),则必须将路径指向该特定部分.(路径:'/ account/login')

不同之处在于我指向整个目录,包括.不同的文件,您只需回复index.html文件.使用listing参数可以决定是否要在网址中显示目录结构.默认值为false.

更多信息:http://hapijs.com/tutorials/serving-files#directory-handler

var Hapi = require('hapi');
var Path = require('path');

var server = new Hapi.Server(8080, 'localhost');


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



server.start(function(){
	console.log('server started');
});
Run Code Online (Sandbox Code Playgroud)


Dav*_*sen 5

受到惰性文档的启发,我通过提供静态目录中的所有内容来解决这个问题.然后我添加了一个onPostHandler来在每次返回404时返回索引文件.然后,客户端路由器可以将重定向发送到静态文件目录中的现有404.html文件.

// Static Assets
server.route({
  method: 'GET',
  path: '/{param*}',
  handler: {
    directory: {
      path: ['app/static'],
      listing: false,
      index: ['index.html']
    }
  }
});

// return index.html for everything else
server.ext('onPostHandler', (request, reply) => {
  console.log('WORD');
  const response = request.response;
  if (response.isBoom && response.output.statusCode === 404) {
    return reply.file('app/static/index.html');
  }
  return reply.continue();
});
Run Code Online (Sandbox Code Playgroud)