Routing to SSR app

情到浓时终转凉″ 提交于 2019-12-24 22:44:52

问题


I am using create-react-app and just added SSR for same.

I just added a middleware to renderToString the react app.

But I am not sure about routing. Should it remain on client or on express(server). If it's on client it is not working. Every request is being served to home page. Quite fair by code I have written. Not sure though how to mend it to serve other pages and still keep the same setup.

Code is below

server/index.js

import express from 'express';
import serverRenderer from './middleware/renderer';

const PORT = 3001;
const path = require('path');
const app = express();
const router = express.Router();

router.use('^/$', serverRenderer);
app.use('/static', express.static(path.join(__dirname, 'assets')));
router.use(express.static(
    path.resolve(__dirname, '..', 'build'),
    { maxAge: '30d' },
));
router.use('*', serverRenderer);
app.use(router);

...

middleware/renderer.js

import {createMemoryHistory } from 'history';

...

const history = createMemoryHistory({
  initialEntries: ['/', '/next', '/last'],
  initialIndex: 0
});

export default (req, res, next) => {
    console.log(req.url); //logs `/` for every route
};

Cannot understand what am I doing wrong here.


回答1:


The reason it will always render the homepage is because you have the following snippet:

const history = createMemoryHistory({
  initialEntries: ['/', '/next', '/last'],
  initialIndex: 0
});`

If you change this to

const history = createMemoryHistory({
    initialEntries: [req.url],
    initialIndex: 0
});

inside your render function it should render the correct URL.

Hope that helps.



来源:https://stackoverflow.com/questions/48746787/routing-to-ssr-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!