LEARNING MEAN STACK: NODE JS – 101
MEAN
Node JS: Web Server Part
- Creating a Simple Web Server
- var http = require('http');
- http.createServer(function (req, res) {
- res.writeHead(200, {'Content-Type': 'text/plain'});
- res.end('Hello World How are you !');
- }).listen(8080,'localhost');
Executing the above code in Node will create a web server and when you will send the request to server using a browser it show below result
2. Outputting HTML file
- var http = require('http');
- var fs = require('fs');
- http.createServer(function (req, res) {
- res.writeHead(200, {'Content-Type': 'text/html'});
- var html = fs.readFileSync(__dirname + '/index.html');
- res.end(html);
- }).listen(8080,'localhost');
The above code reads the index.html file and produces and HTML output.
index.html
- <html>
- <head>
- <title>
- Hello Node
- </title>
- <body>
- <h1>
- Hello Sarthak!
- </h1>
- </body>
- </head>
- </html>
Output when you send a request to localhost:8080
3. Outputting Dynamic HTML Content
- var http = require('http');
- var fs = require('fs');
- http.createServer(function (req, res) {
- res.writeHead(200, {'Content-Type': 'text/html'});
- var html = fs.readFileSync(__dirname + '/index2.html','utf8');
- var msg = "Hello Sarthak, this is dynamic content!!!";
- html = html.replace('{message}', msg);
- res.end(html);
- }).listen(8080,'localhost');
index.html
- <html>
- <head>
- <title>
- Hello Node
- </title>
- <body>
- <h1>
- {message}
- </h1>
- </body>
- </head>
- </html>
4. Outputting JSON
- var http = require('http');
- http.createServer(function (req, res) {
- res.writeHead(200, {'Content-Type': 'application/json'});
- var obj = {
- firstname: 'Sarthak',
- lastname: 'Srivastava'
- };
- res.end(JSON.stringify(obj));
- }).listen(8080,'localhost');
MIME type is changed to ‘application/json‘
5. Routing
Means when we hit different URLs we should get Navigated to different pages.
- var http = require('http');
- var fs = require('fs');
- http.createServer(function (req, res) {
- if(req.url === '/'){
- res.writeHead(200, {'Content-Type': 'text/plain'});
- res.end('Hello World How are you !');
- }
- else if(req.url === '/more'){
- res.writeHead(200, {'Content-Type': 'application/json'});
- var obj = {
- firstname: 'Sarthak',
- lastname: 'Srivastava'
- };
- res.end(JSON.stringify(obj));
- }
- else{
- res.writeHead(404);
- res.end();
- }
- }).listen(8080,'localhost');
when you hit localhost:8080
it displays this
but when you hit localhost:8080/more
it displays this
else for wrong URL it will show blank or 404.
Comments
Post a Comment