Learning react also has a period of time, the use of react after the first page rendering speed and SEO has not been ideal. I'm going to look at react's magical service-side rendering.
React service-side rendering can only use Nodejs as the server-side language to implement the front-end isomorphism, the react component is parsed in the background and the HTML string is generated to return to the view page.
Why can I parse the react component in the background? Because of Node. JS is a JavaScript runtime environment, NODEJS and JavaScript syntax is basically the same, so nodejs can normally parse react components.
First, prepare the action
1. Install Nodejs and install Express
Installation Nodejs Tutorial: http://www.cnblogs.com/pigtail/archive/2013/01/08/2850486.html
Install Express Tutorial: http://www.expressjs.com.cn/starter/installing.html
2, install NODE-JSX (make Nodejs support JSX syntax)
$ NPM Install NODE-JSX
3. Installing the Ejs template engine
$ NPM Install Ejs
4, choose Ejs Template engine to parse the HTML view file (Configure the Express Framework application App.js), need to modify the configuration as follows:
1 var ejs = require (' Ejs '); 2 app.engine ('. html ', ejs.__express); //Parsing an HTML view file using the Ejs template engine 3 app.set (' View engine ', ' html ');
Second, the concrete realization is as follows:
Express Route:
1"Use Strict";2 varExpress = require (' Express ');3 varRouter =Express. Router ();5Require ("NODE-JSX"). Install ();//Install "NODE-JSX", install the module can make Nodejs compatible JSX syntax6 varReact=require ("React");7 varCom=require ('.. /component/test.js '). Component//Introducing REACT Components8Router.get ('/',function(req, res, next) {9 varHtml=react.rendertostring (Com ({name: "Dudeyouth"}))//to pass parameters to a component and parse it into an HTML string using the Rendertostring methodTenRes.render ("index", {component:html});//rendering to the interface One }); AModule.exports = router;
React components:
1"Use Strict";2 varReact=require ("React");3 varComponent=react.component;4 class Test extends component{5 render () {6 return This.props.name}7 }8 }9module.exports={"Component":function(props) {Ten return<test {...props}/> One}};
View (using the Ejs template engine):
1 <HTML>2 <Head>3 <title>Dudeyouth Blog</title>4 <MetaCharSet= "Utf-8" />5 <Linkhref= "Css/index.css"rel= "stylesheet"/>6 <Linkhref= "Css/style.css"rel= "stylesheet"/>7 </Head>8 <Body>9 <DivID= "Container"><%-Component%></Div> <!--parse HTML string with Ejs template-- Ten </Body> One </HTML>
React service-Side rendering (isomorphic)