从我阅读的所有内容中,我的经历听起来很奇怪。但是当我想传递值时,似乎express.static
正在根目录提供文件。
要进行布局,我有一个:
我的存储库已布局,因此文件夹结构看起来像这样:
/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,则会得到传递的值)
答案 0 :(得分:0)
已解决。我不得不更改两件事:
app.use(express.static(path.join(__dirname, '../../build')));
app.use('\static', express.static(path.join(__dirname, '../../build')));
(可以使用\static
以外的其他方式package.json
中,添加一个homepage
设置。我放了"homepage": "/static"
(这是我不明白自己缺少的部分)。本节中的信息:https://create-react-app.dev/docs/deployment/,但直到我在另一个存储库中看到它之前,我还是不理解它。