我需要在create-react-app中使用Hapi,其中Hapi充当api请求的代理,并为React应用程序提供服务。
我正在尝试使路由正常工作,但它似乎不能与当前的Hapi配置一起工作。
下面是我的服务器代码:
const Path = require('path');
const Hapi = require('hapi');
const Inert = require('inert');
const init = async () => {
const server = new Hapi.Server({
port: process.env.PORT || 5000,
routes: {
files: {
relativeTo: Path.join(__dirname, '../build')
}
}
});
await server.register(Inert);
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: '.'
}
}
});
const options = {
ops: {
interval: 1000
},
reporters: {
myConsoleReporter: [
{
module: 'good-console',
args: [{ request: '*', response: '*' }]
},
'stdout'
]
}
};
await server.register({
plugin: require('good'),
options,
});
await server.start();
console.log('Server running at:', server.info.uri);
};
init();打开localhost:5000时,index.html文件加载正常。我已经在react-router部分中配置了路由/dashboard。点击localhost:5000/dashboard会得到404分。
问题:
create-react-app 中弹出的情况下将其配置为热重新加载create-react-app
注意:当使用npm start运行react应用程序时,路由会起作用。但这是在没有运行Hapi服务器的情况下进行的。
我刚开始使用Hapi,所以感谢任何人的指点。
发布于 2021-05-05 11:16:57
这就是我是如何做到的。测试过了。版本"@hapi/hapi": "^20.0.1"。
const path = require("path")
const Hapi = require('@hapi/hapi')
const Boom = require('@hapi/boom');
const server = Hapi.server({
port: 3000,
host: '0.0.0.0',
routes: {
files: {
relativeTo: path.join(__dirname, 'YOU BUILD REACT DIR')
}
}
});
(async () => {
await server.register([
require('vision'),
require('inert')
]);
server.route(
[{
method: 'GET',
path: '/{path*}',
options: {
ext: {
onPreResponse: {
method(req, h) {
//for other path prefix /Api
const isApi = req.path.substr(1)
.toLowerCase()
.trim()
.split('/')[0]
.replace(/\//g, "") === "api"
const response = req.response
if (response && req.response.output && req.response.output.statusCode === 404) {
if (isApi)
return Boom.notFound("Not Found")
return h.file('index.html');
}
return h.continue
},
}
}
},
handler: {
directory: {
path: ".",
listing: false,
index: true
}
}
},
{
method: 'GET',
path: '/Api/test',
handler: () => "OK"
}
])
await server.start();
console.log('Server running on %s', server.info.uri)
})()https://stackoverflow.com/questions/55649840
复制相似问题