【问题标题】:Server side rendering (Express/React), serving up files without route defined服务器端渲染(Express/React),提供未定义路由的文件
【发布时间】:2020-11-04 23:27:56
【问题描述】:

从我读过的所有内容来看,我的经历听起来很奇怪。但是当我想传递值时,express.static 似乎在根目录提供文件。

为了说明,我有一个:

  • React 应用程序,我使用 create-scripts 构建生产环境
  • Express 应用程序,在与上述相同的存储库中,应该提供文件

我的存储库已布局,因此文件夹结构如下所示:

/build (React js files after building src)
/dist (Express js files after building server)
/server (Express in typescript)
/src (React in typescript)

/server/index.ts 我有类似的东西:

const app = express();
export function configureApp() {
    // CONFIGURATIONS
    app.set('env',config.environmentName.toLowerCase());
    app.set('port', config.port);
    app.set('https', config.https);

    // MIDDLEWARE SETUP
    app.use(compression());
    app.use(REQUEST_LOGGER);
    app.use(ERROR_LOGGER);
    app.use(express.json());

    // Below here is where it troubles me
    app.use(express.static(path.join(__dirname, '../../build'))); // This will always run on localhost: 080

    // This is never called. I know this code will work as when I put it under a different path (changes `/` to `/blah`, I can see this stuff. But this is never called for localhost:8080 which means I can't pass anything to the view
    app.use('/', (req: Request, res: Response ) => {
        const store = configureStore({
            'userSession':{
                'userName' : 'fakeUserName'
            }
        });

        const reduxState = JSON.stringify(store.getState());

        const filePath = path.join(__dirname, '../../../build', 'index.html');
        fs.readFile(filePath, 'utf8', (err, htmlData) => {
            return res.send(htmlData.replace('__REDUX_STATE__={}', `__REDUX_STATE__=${reduxState}`));
        })
}

export default app

当我在localhost:8080 上启动页面时,它会显示该页面,但是,当我想将值传递到上述行时,它不起作用。它只会在不在根级别时传递值(例如 localhost:8080/,如果我将其移动到 localhost:8080/blah,我会得到传入的值)

【问题讨论】:

    标签: javascript reactjs server-side-rendering static-files


    【解决方案1】:

    已解决。我必须改变两件事:

    1. 选择应从何处提供静态文件的路径
    • 来自:app.use(express.static(path.join(__dirname, '../../build')));
    • 至:app.use('\static', express.static(path.join(__dirname, '../../build')));(除了\static,还可以使用其他东西
    1. package.json 中,添加homepage 设置。我输入了"homepage": "/static"(这是我不明白我错过的部分)。本节中的信息:https://create-react-app.dev/docs/deployment/ 但直到我在另一个 repo 中看到这个我才明白它

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 2017-04-15
      • 2020-12-11
      • 2015-04-19
      • 2018-04-26
      • 1970-01-01
      • 2016-07-16
      • 2015-12-23
      • 2018-03-13
      相关资源
      最近更新 更多