Routing to SSR app

2019-08-26 23:27发布

问题:

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.