[英]Server side rendering (Express/React), serving up files without route defined
From everything I've read, my experience sounds strange.从我读过的所有内容来看,我的经历听起来很奇怪。 But it seems like
express.static
is serving up files at root when I would like to pass in values.但是当我想传入值时,
express.static
似乎正在以根目录提供文件。
To lay it out, I have a:为了布置它,我有一个:
My repository is laid out so the folder structure looks something like this:我的存储库已布局,因此文件夹结构如下所示:
/build (React js files after building src)
/dist (Express js files after building server)
/server (Express in typescript)
/src (React in typescript)
In /server/index.ts
I have something like:在
/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
When I start up the page on localhost:8080
, it shows the page, however, when I want to pass in values to the the above line, it does not work.当我在
localhost:8080
上启动页面时,它显示了页面,但是,当我想将值传递给上面的行时,它不起作用。 It will only pass in the values when it is not at the root level (eg localhost:8080/, if I move it to localhost:8080/blah, I get the values passed in)它只会在它不在根级别时传入值(例如 localhost:8080/,如果我将它移动到 localhost:8080/blah,我会得到传入的值)
Resolved.解决。 I had to change two things:
我不得不改变两件事:
app.use(express.static(path.join(__dirname, '../../build')));
app.use(express.static(path.join(__dirname, '../../build')));
app.use('\\static', express.static(path.join(__dirname, '../../build')));
app.use('\\static', express.static(path.join(__dirname, '../../build')));
(can use something else besides \\static
\\static
之外的其他东西package.json
, add a homepage
setting.package.json
,添加homepage
设置。 I put "homepage": "/static"
(this was the part I didn't understand I was missing)."homepage": "/static"
(这是我不明白我错过的部分)。 Info in this section: https://create-react-app.dev/docs/deployment/ but I didn't understand it until I saw this in another repo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.