【问题标题】:Static Script file overrides the GET method Server-side Rendering静态脚本文件覆盖 GET 方法服务器端渲染
【发布时间】: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.htmlindex.cssindex.bundle.js .

【问题讨论】:

    标签: node.js reactjs heroku deployment server-side-rendering


    【解决方案1】:

    你需要在你的 package.json 中添加 heroku-postbuild 命令 您的命令类似于

    scripts:{
        ...
        "build": ***,
        "heroku-postbuild": "npm install && npm run build",
    }
    

    这将运行并安装您的依赖项,并将运行构建命令。

    尝试删除'return'关键字

    res.send(
    data.replace(
     <div id="root"></div>',
     <div id="root">${app}</div>`
     )  
    )
    

    端口应该是 进程.env.PORT || 3000

    就是这样。它现在应该可以工作了。

    【讨论】:

    • 虽然我已经有了postinstall 脚本,虽然我不知道额外的heroku-postbuild 会做什么,但我尝试将它添加到文件中,但我仍然收到应用程序错误。不过这次的日志有点不同。
    • 我已经用更新的日志为您的解决方案编辑了问题。请看一看。
    • 我已经编辑了答案,您可以通过更新 PORT 尝试此解决方案
    • 恐怕还是不行!我已经用最近的日志替换了您的答案日志。请阅读日志!
    • 尝试评论 RenderToString 并返回一些随机字符串。看看有没有效果!您的应用程序在本地环境中运行良好吗?
    【解决方案2】:

    解决了!!!

    代码有两个问题-

    1. 第一个是 app.get() 方法不运行的问题是通过将 app.use() 语句移到前一个语句下方来解决的。

    不过,我还是不太明白其中的原因,因为我认为中间件仍然会在路由方法中的回调函数之前运行。如果你知道这里发生了什么,请通过 cmets 告诉我!

    1. 导致start 脚本失败的第二个问题是因为我将@babel/core 用作dev-dependency。所以我只将它重新安装为 依赖项,并修复了错误。

    如果有人能向我解释第一点,我将不胜感激!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-27
      • 2014-11-03
      • 2016-10-08
      • 2012-06-29
      • 2017-12-11
      • 2012-06-03
      • 2015-05-28
      • 2011-08-18
      相关资源
      最近更新 更多