Sunday, 24 February 2019

A simple REACT node.js example

 Create Hello.js REACT script
helloAli.js
'use strict';
//document.write("Hello World!");
const name = 'Ali Riza SARAL';
const element = &lth1&gtHello from {name}&lt/h1>

ReactDOM.render(
  element,
  document.getElementById('root')
);

Create the html that will insert the REACT jscript.
index4.html
&lt!doctype html&gt
&lthtml&gt

&lthead&gt
    &ltmeta charset="utf-8"&gt

    &lttitle&gtHello React!&lt/title&gt

    &ltscript src="https://unpkg.com/react@16/umd/react.development.js"&gt&lt/script&gt
    &ltscript src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"&gt&lt/script&gt
    &ltscript src="https://unpkg.com/babel-standalone@6.26.0/babel.js"&gt&lt/script&gt
&lt/head&gt

&ltbody&gt

    &ltdiv id="root"&gt&lt/div&gt

    &ltscript type="text/babel" src="helloAli.js"&gt&lt/script&gt

&lt/body&gt

&lt/html&gt

Create the server that will display the html.

var url = require('url');

// Create a server
http.createServer( function (request, response) { 
   // Parse the request containing file name
   var pathname = url.parse(request.url).pathname;
  
   // Print the name of the file for which request is made.
   console.log("Request for " + pathname + " received.");
  
   // Read the requested file content from file system
   fs.readFile(pathname.substr(1), function (err, data) {
      if (err) {
         console.log(err);
        
         // HTTP Status: 404 : NOT FOUND
         // Content Type: text/plain
         response.writeHead(404, {'Content-Type': 'text/html'});
      } else {           
         //Page found            
         // HTTP Status: 200 : OK
         // Content Type: text/plain
         response.writeHead(200, {'Content-Type': 'text/html'});  
        
         // Write the content of the file to response body
         response.write(data.toString());                   
      }
     
      // Send the response body
      response.end();
   });  
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Run procedure in the same library of all the above:
1-      Start the server with
Node server
2-      Open a browser
3-      Run the REACT through html

Notes:  You do not have to use the  node.js server given here.  Any server Tomcat, Glassfish will work OK.