【发布时间】:2020-09-21 05:37:30
【问题描述】:
存储库-https://github.com/sapinder-pal/Rest-Countries-App-ReactJS-SASS
我正在尝试将我的 React 应用程序转换为 SSR 系统。虽然它可以在 localhost 上运行,但在部署到 Heroku 时会引发应用程序错误。构建日志显示成功,但访问该 url 时抛出 应用程序错误。
请查看 EDIT 1,我已在其中说明了根本错误。
应用程序日志-
2020-09-21T05:23:05.915898+00:00 app[web.1]: npm ERR! rest-countriers@1.0.0 start: `node server/index.js`
2020-09-21T05:23:05.916046+00:00 app[web.1]: npm ERR! Exit status 1
2020-09-21T05:23:05.916211+00:00 app[web.1]: npm ERR!
2020-09-21T05:23:05.916335+00:00 app[web.1]: npm ERR! Failed at the rest-countriers@1.0.0 start script.
2020-09-21T05:23:05.916489+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-09-21T05:23:06.005989+00:00 app[web.1]:
2020-09-21T05:23:06.006055+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-09-21T05:23:06.006056+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2020-09-21T05_23_05_918Z-debug.log
2020-09-21T05:23:06.234287+00:00 heroku[web.1]: Process exited with status 1
2020-09-21T05:23:06.275353+00:00 heroku[web.1]: State changed from starting to crashed
server/index.js-
require('ignore-styles');
require('@babel/register')({
ignore: [/(node_module)/],
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: ['@babel/transform-runtime']
});
require('./server');
server/server.js-
import express from 'express';
import fs from 'fs';
import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {StaticRouter} from 'react-router-dom';
import App from '../src/App';
const PORT = process.env.PORT || 8080;
const app = express();
app.use(express.static(path.resolve('./build')))
app.get('*', (req, res) => {
fs.readFile(path.resolve('./build/index.html'), 'utf-8', (err, data) => {
if (err) {
console.log(err);
return res.status(500).send('Some error happened');
}
const context = {};
const app = ReactDOMServer.renderToString(
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
)
return res.send(
data.replace(
'<div id="root"></div>',
`<div id="root">${app}</div>`
)
);
});
});
app.listen(PORT, () => {
console.log(`App launched on ${PORT}`);
});
编辑 1-
看起来我找到了根本错误但不太清楚原因-
/**** app.get() WORKS ONLY IF I DON'T SERVER THE 'BUILD' FOLDER. ****/
app.use(express.static(path.resolve('./build')));
/**** This function doesn't log anything if the *build* folder is served.
I got assured when I visited **Network** tab in devtools where I saw that
the *initial preview* for html file is blank, which means the file is not
rendered server-side ****/
app.get('*', (req, res) => {
console.log('got request');
....
}
我在 build 文件夹中有 index.html、index.css 和 index.bundle.js .
【问题讨论】:
标签: node.js reactjs heroku deployment server-side-rendering