微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

服务器端渲染快速/响应,提供未定义路由的文件

如何解决服务器端渲染快速/响应,提供未定义路由的文件

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

要进行布局,我有一个

  • 反应性应用程序,我使用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,则会得到传递的值)

解决方法

已解决。我不得不更改两件事:

  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/,但直到我在另一个存储库中看到它之前,我还是不理解它。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。