【发布时间】: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