永久违反:浏览器历史记录需要DOM

时间:2018-09-03 10:56:50

标签: reactjs react-router serverside-rendering

对于服务器端,BrowserRouter将不起作用,因此将根据documentation使用StaticRouter。我在做同样的事情,但仍然出现错误。以下是我的设置

  

永久违反:浏览器历史记录需要DOM

import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { StaticRouter as Router } from 'react-router';

// import our main App component
import App from '../src/App';

const path = require('path');
const fs = require('fs');

export default (req, res) => {
  // get the html file created by CRA's build tool

  console.log('url : ', req.baseUrl);


  const filePath = path.resolve(__dirname, '..', '..', 'build', 'index.html');

  fs.readFile(filePath, 'utf8', (err, htmlData) => {
    if (err) {
      console.error('err', err);
      return res.status(404).end();
    }

    // render the app as a string
    const html = ReactDOMServer
      .renderToString(<Router location={req.baseUrl}>
        <App />
                      </Router>);

    // now inject the rendered app into our html and send it
    return res.send(htmlData
      .replace('<div id="root"></div>', `<div id="root">${html}</div>`));
  });
};

0 个答案:

没有答案