簡體   English   中英

nodejs&react:根據請求渲染另一個HTML文件

[英]nodejs & react: render another HTML file upon request

我正在嘗試在我們的項目中實現amp頁面。

到目前為止,我已經提出了以下解決方案:如果url中有一個查詢,例如: myurl.com?amp=1 ,則該頁面將在必要的標記下完全重繪。 問題是,目前,我們的服務器已配置為可以在2個html文件中進行選擇,如果出錯,則帶有錯誤的標記,如果沒有,則返回常規索引。 它是這樣的:

yield this.render('index', {
        state: encodeURIComponent(JSON.stringify(state)),
        body: renderToString(
            <Provider store={store}>
                <RouterContext {...props}/>
            </Provider>
        )
    });

和錯誤

app.use(isProduction ? function * error(next) { // error handler
    try {
        yield next;
        if (this.response.status === 404 && !this.response.body) {
            this.throw(404);
        }
    } catch (err) {
        const STATUS_CODES = require('http').STATUS_CODES;
        const seo = require('app/modules/seo').initialState;

        this.status = err.status = err.status || 500;
        if (err instanceof URIError) {
            this.redirect('/search');
            return;
        }
        err.message = STATUS_CODES[this.status];
        this.app.emit('error', err, this);

        yield this.render('error', {
            assets,
            err,
            seo: {...seo, long_title: `${err.status} – ${seo.long_title}`}
        });
    }
} : error());
componentDidMount() {
        if (this.state.isAmp) {
            document.write(expotedAmpMarkup(this.props.body))
        };
}

請告訴我,在URL上有請求時,如何在服務器端禁用標准標記?

是否可以在服務器端進行新頁面的繪制?

對於造成混淆的文字,我事先表示歉意。 我對提出一個有力的問題了解得很少,除了這個論壇之外,我沒有人要尋求幫助。

如有必要,可以發送整個服務器和Webpack配置。 准備回答任何問題。 謝謝。

您可以根據需要在SSR上呈現所需的任何頁面。

您可以看一下我處理路線的SSR應用程序: https : //github.com/tornado1979/ssr-rentalcars

一些關鍵點如下:

客戶端“ index.js”:

.....
import { BrowserRouter } from 'react-router-dom'
import { renderRoutes } from 'react-router-config'

import store from './store'
import Routes from './components/Router/routes'


ReactDOM.hydrate(
<Provider store={store}>
  <BrowserRouter>
    <div>{renderRoutes(Routes)}</div>
  </BrowserRouter>
</Provider>,
document.getElementById('root'),
)

客戶端“ routes.js”,在這里放置所有頁面

export default [
{
  ...App,
  routes: [
   {
     ...HomePage,
     description: "Compare car hire deals and find the cheapest prices in.",
    keywords: 'car hire, cheap car hire, car rental uk,  rent a car, car rentals, uk car car, cheap car rentals spain, cheap car rental usa, carrentals, rent car, car hire comparison, carrental, carhire, compare car hire, car rental comparison, rentalcars, rental cars',
    path: '/home',
    title: '.......',
  },
  {
    ...About,
    description: 'About Compare car hire deals...',
    keywords: 'car hire, ...',
    path: '/about',
    title: 'About - Rentalcars',
  },
  {
    ...NotFoundPage,
    description: '',
    keywords: '',
    title: 'page not found - Rentalcars',
  },
],
 },
  ]

服務器端,“ index.js”, 您收到請求並將正確的組件發送到客戶端 //您需要此路由器:
import { matchRoutes } from 'react-router-config'

app.get('*', (req, res) => {
  const store = createStore()
   // Initialize and load data into the store
   const promises = matchRoutes(Routes, req.path).map(({ route }) => {
    return route.loadData ? route.loadData(store) : null
  })

Promise.all(promises).then(() => {
  const context = {}
  const content = renderer(req, store, context)

  if (context.notFound) {
    res.status(404)
  }

  return res.send(content)
 }).catch(error => res.status(500).send(`Internal Server Error:, 
${error}`))
})

渲染pagestore並將其傳遞給客戶端“ render.js”

export default (req, store, context = {}) => {
const content = renderToString(
<Provider store={store}>
  <StaticRouter context={context} location={req.path}>
    <div>{renderRoutes(Routes)}</div>
  </StaticRouter>
</Provider>,

)const helmet = Helmet.renderStatic()

return( <!DOCTYPE html> <html ${helmet.htmlAttributes.toString()}> <head> <meta charset="UTF-8"> ${helmet.title.toString()} ${helmet.meta.toString()} </head> <body ${helmet.bodyAttributes.toString()}> <div id="root">${content}</div> <script> window.INITIAL_STATE = ${serialize(store.getState())} </script> <script src="bundle.js"></script> </body> </html> )}

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM