2016-10-03 50 views
1

我正在研究isomorphoc react/flux應用程序並使用swig來呈現內容。 但是,當我打開網站時,它首先顯示帶有{{ html|safe }}輸出標籤的空白頁面,然後將實際內容呈現到我的index.html文件中。Swig模板在呈現內容之前顯示輸出標記

在我server.js代碼如下:

res.status(200).send(swig.renderFile(__dirname + '/public/index.html', {html: html}));

任何想法如何避免這種情況?此外,這是否會阻止服務器渲染?抓取頁面時,Google抓取工具是否只能看到輸出標記?

謝謝。

編輯:

require('babel-register'); 

var express = require('express'); 
var app = express(); 
var compression = require('compression'); 

var path = require('path'); 
var http = require('http'); 
var swig = require('swig'); 
var React = require('react'); 
var ReactDOM = require('react-dom/server'); 
var Router = require('react-router'); 
var routes = require('./app/routes'); 

app.use(compression()); 

app.use(express.static(path.join(__dirname, 'public'))); 

// create react router 
app.use(function(req, res){ 
    Router.match(
     { 
      routes: routes.default, 
      location: req.url 
     }, 
     function(err, redirectLocation, renderProps){ 
      if(err){ 
       res.status(500).send(err.message); 
      } else if(redirectLocation){ 
       res.status(302).redirect(redirectLocation.pathname +  redirectLocation.search); 
      } else if(renderProps){ 
       var html = ReactDOM.renderToString(React.createElement(Router.RouterContext, renderProps)); 
      var page = swig.renderFile(__dirname + '/public/index.html', {html: html}); 
      res.status(200).send(page); 
     } else { 
      res.status(404).send('Page not found'); 
     } 
    } 
); 
}); 
// and so on ... 

這裏是我的routes.js

import React from 'react'; 
import { Route } from 'react-router'; 
import App from './components/App'; 
import Home from './components/Home'; 

export default (
    <Route component={App}> 
     <Route path="/" component={Home} /> 
    </Route> 
); 
+0

可以顯示更多相關的代碼,特別是res.status ...來自哪裏的app.get。/public /目錄是否公開? – Molda

+0

增加了更多的代碼。問題不在於它沒有工作,問題是,用戶在內容呈現之前看到swig輸出標記1秒。 – eScoo

+0

我明白了,事情是swig標記'{{html | safe}}'不應該離開服務器。它應該永遠不會到達客戶端,因爲swig應該替換它在服務器上。在res.status(200).send(page)之前添加console.log('HTML',page);'是還在那裏的swig標籤?它不應該! – Molda

回答

0

中的index.html是問題。將其重命名爲「site.html」,現在將服務器端渲染工作在根路由上,並且不會顯示任何swig標記。

相關問題