【问题标题】:How to serve a React page from Hapijs server regardless of route无论路由如何,如何从 Hapijs 服务器提供 React 页面
【发布时间】:2019-08-09 05:28:13
【问题描述】:

我有一个提供 api 路由的 hapijs 服务器和一个 React 应用程序。我使用惰性和带有目录参数的处理程序为反应应用程序提供服务。但是,由于我在路径 {param*} 中使用的参数会自动提供“index.html”,因此 hapijs 只会在没有参数的情况下提供响应页面。这是有道理的,因为 hapi 会在目录中查找参数并返回错误 404。

现在,我想要做的是无论参数(甚至路由)如何都可以为反应页面提供服务,并让反应处理 404 错误。我似乎找不到合法的解决方案。使用目录处理程序不允许出现 404,并且使用函数处理程序来服务页面将在没有 css 或 js 脚本的情况下提供页面。

我使用了以下教程并阅读了其他教程,但无济于事。 https://medium.com/@notrab/using-create-react-app-with-hapi-js-8f4ef3dcd311

//manifest.js
module.exports = {
    server: {
        port: process.env.PORT,
        router: { stripTrailingSlash: true },
        routes: {
            files: {relativeTo: path.join(__dirname, '../client/build')},
            cors: {origin: ["*"],}
        }
    },
    register: {
        plugins: [
            { plugin: require('inert') },
            {
                plugin: 'vision',
                options: {
                    engines: { html: require('handlebars') },
                    path: path.join(__dirname, '../client/build')
                }
            },
            {
                plugin: require('./controllers/home'),
            },
        ],
    }
// controller/home
module.exports.register = function(server, options, next) {
server.route({
    method: 'GET',
    path: '/{param*}',
    handler: {
    directory: {
    path: path.join(__dirname, "../../../client/build/"),
    listing: false,
    index: ['index.html']
}

// the following handler serves the page but not the css or js
    //handler: (request, h) => {
    //    return h.file("index.html", {confine: false});
    //}

【问题讨论】:

    标签: node.js reactjs hapijs


    【解决方案1】:

    使用Inert时,由于您已将relativeTo设置为已解析client/build目录,因此无需再次输入完整路径。

    您也可以完全删除index: ['index.html'],因为它会默认查找索引文件

    module.exports.register = function(server, options, next) {
    server.route({
        method: 'GET',
        path: '/{param*}',
        handler: {
            directory: { path: '.' }
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-03
      • 2017-10-17
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2018-03-12
      • 2021-02-15
      相关资源
      最近更新 更多