[英]Handling routes with express for react app?
I have a react app running fine. 我有一个React应用运行良好。 I wanted to deploy it using express static. 我想使用express static部署它。 So i have given the express-static path to the build folder in client. 所以我给了客户端的build文件夹一个express-static路径。 The '/' routes works fine and the React router takes the job from there. “ /”路由工作正常,React路由器从那里开始工作。 But when i refresh the page, express is not able to send the build file, instead gives an error 但是当我刷新页面时,express无法发送构建文件,而是给出了错误
Tried to use * all routes in express to the same react build file 试图使用*所有路由到同一React构建文件
app.use(express.static(path.join(__dirname, '../client/', 'build')));
app.get('*', function(req, res) {
res.sendFile('index.html', function(err) {
if (err) {
res.status(500).send(err);
}
});
});
Instead of writing down(duplicating) all the routes in express again, wanted a simpler solution 与其再次写下(复制)所有路线,不如想要一个更简单的解决方案
Try this settings : 尝试以下设置:
app.use(express.static(path.join(__dirname, 'build')));
app.get('*', function (req, res, next) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const CLIENT_APP_PATH = '../client/build';
app.use(express.static(CLIENT_APP_PATH));
// ...express middlewares, rest, etc...
// in the end of app routing
// serves frontend application
app.get('/*', (req, res) => {
res.sendFile(path.resolve(`${CLIENT_APP_PATH}/index.html`), { root: __dirname }, err => {
if (err) {
res.status(500).send(err);
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.