路由到 SSR 应用程序
Routing to SSR app
我正在使用 create-react-app 并为此添加了 SSR。
我刚刚添加了一个中间件来 renderToString 反应应用程序。
但是我不确定路由。它应该保留在客户端还是 express(服务器)上。如果它在客户端上,则无法正常工作。每个请求都被发送到主页。根据我编写的代码,相当公平。不确定如何修复它以服务于其他页面并仍然保持相同的设置。
代码如下
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
};
无法理解我在这里做错了什么。
它总是呈现主页的原因是因为您有以下代码段:
const history = createMemoryHistory({
initialEntries: ['/', '/next', '/last'],
initialIndex: 0
});`
如果将其更改为
const history = createMemoryHistory({
initialEntries: [req.url],
initialIndex: 0
});
在您的渲染函数中,它应该渲染正确的 URL。
希望对您有所帮助。
我正在使用 create-react-app 并为此添加了 SSR。
我刚刚添加了一个中间件来 renderToString 反应应用程序。
但是我不确定路由。它应该保留在客户端还是 express(服务器)上。如果它在客户端上,则无法正常工作。每个请求都被发送到主页。根据我编写的代码,相当公平。不确定如何修复它以服务于其他页面并仍然保持相同的设置。
代码如下
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
};
无法理解我在这里做错了什么。
它总是呈现主页的原因是因为您有以下代码段:
const history = createMemoryHistory({
initialEntries: ['/', '/next', '/last'],
initialIndex: 0
});`
如果将其更改为
const history = createMemoryHistory({
initialEntries: [req.url],
initialIndex: 0
});
在您的渲染函数中,它应该渲染正确的 URL。
希望对您有所帮助。