The Eduladder is a community of students, teachers, and programmers just interested to make you pass any exams. So we help you to solve your academic and programming questions fast.
In eduladder you can Ask,Answer,Listen,Earn and Download Questions and Question papers.
Watch related videos of your favorite subject.
Connect with students from different parts of the world.
Apply or Post Jobs, Courses ,Internships and Volunteering opportunity. For FREE
See Our team
Wondering how we keep quality?
Got unsolved questions? Ask Questions

Nodejs-Interview-questions-basic-->View question

Can You Create HTTP Server In Nodejs?

Can You Create HTTP Server In Nodejs, Explain The Code Used For It?



Asked On2019-06-17 14:49:14 by:gokilapriya

Taged users:


Likes:
Be first to like this question

Dislikes:
Be first to dislike this question
Talk about this  Like  Dislike
View all qusetions
Answers

we are going to create a simple HTTP Server with Node.js. The server is going to be able to take a request that you sent via the browser and also respond to those requests that you sent to it. We'll look at some more modules.

Our document Structure Our document has some basic HTML in it. We'll use the file to load via the HTTP server. Also, there's a file called server.js and a logo file as well. On the right-hand side, you can see I have opened the terminal and the browser:


Let's import the HTTP module by writing var http = require('http'); This is the module that is built inside node.js.

Create a server by writing http.createServer(). listen(7000) the server is created but we need to write some function which is going to take request also it's going to have a callback response.

So when any kind of request comes in, we are going to have a generic response by writing:

response.writeHead(200, {'Content-type': 'text/plan'}; 

because every HTTP request has a head and a response code. 200 in our case, which is a success response. Also, they have other parameters but in our case, we'll have content-type and the value is going to be text/plan. The response has another property respone.write('Hello Node JS Server Response') and the last value is going to be response.end();

var http = require('http');http.createServer(function(request, respone){  respone.writeHead(200, {'Content-type':'text/plan'});  response.write('Hello Node JS Server Response');  response.end( );}).listen(7000);

Run the code by writing node server hit enter and go to the link localhost:7000 and you can see http server has been loaded and it shows the generic message on the browser. Also no matter what you put ahead of 7000 port like such:

localhost:700/randomtext 

or anything you put there and refresh the page, it will always display the generic text that we have. Because the server does not take into consideration on what the request parameters are:


We can console.log(request); to see what's happening. Close the server and restart it and refresh the browser again. You will see a lot of information in the console. We can look for the url one, which has the value of whatever was written in the browser url section. We put aziz so you can see below the /aziz was printed because it captured the request. Based on whatever the url, if let's say index.html is there, run the index.html file etc

But the request can also be complicated like it could be a query string parameter like such users?name=aziz&access=full. In the image below /users is the link while name=aziz&access=full is the query string.

There are some other modules that can process or parse the path and the query string. So we can say write a module var url = require('url'); this module can help us parse the URL. So we can say pathName = url.parse(request.url).pathname;

  var http = require('http');var url = require('url');
  http.createServer(function(request, respone){  respone.writeHead(200, {'Content-type':'text/plan'});  response.write('Hello Node JS Server Response');  response.end( );
pathName= url.parse(request.url).pathname;
   console.log(pathName);  
}).listen(7000);

So in our case, the pathName is going to be the url. Run the code by writing node server hit enter and It printed users which is the path name and also it shows favicon.ico which is the default thing that it does. Favicon shows at the top of the website as shown below

We can process the query string as well. We can add another module by writing like such var querystring = require('querystring'); also make sure that your code looks same like the way it does in the screenshot below

  var http = require('http');var url = require('url');
var querystring = require('querystring');http.createServer(function(request, respone){  respone.writeHead(200, {'Content-type':'text/plan'});  response.write('Hello Node JS Server Response');  response.end( );   pathName= url.parse(request.url).pathname;
   query= url.parse(request.url).query;   console.log('pathName' + pathName);  
   console.log('query' + query);}).listen(7000);

Refresh the terminal one more time and you can see the pathName is the /users and the query is the name=aziz&access=full.

Now, the querystring module can process and make the query into an object and we can read whatever query string we want to read. if we go to Google and search anything, you see at the URL, the source id which is highlighted is a query string.

Now, let's see if we can load the html via the server. I'll write localhost:7000/file.html and hit enter and you will see that it still printed the same generic information like such:

Now, we are going to use our file system module to read the files. We can write

var = require('fs'); also create the directory of the file which you want to read by writing fs.readFile(__dirname + pathName and then run a callback functions. We can have two callback objects, if the error occurs, show the response code of 404 which is the code for page not found, if the page loads successfully then show the data.

var http = require('http');
var url = require('url');
var querystring = require('querystring');
var = require('fs');
http.createServer(function(request, respone){
   pathName = url.parse(request.url).pathname;
   fs.readFile(__dirname + pathName, function(err, data){
      if(err){
         respone.writeHead(404, {'Content-type':'text/plan'});
         response.write('Page Was Not Found');
         response.end();
       } else {
         respone.writeHead(200, {'Content-type':'text/plan'});
         response.write(data);
         response.end( );
   }).listen(7000);


Refresh the server and the browser you will see the HTML file on the browser:


You may notice that it's showing the simple text, which doesn't look good so you can remove the following:


Restart the server and refresh the page and you will see that the HTML page has been loaded.


If you try to open index.html file which does not exist in our case, it won't open and it will give you an error. you can also stringify the error by writing JSON.stringify(err));


Restart the server and refresh the browser and you will see it gives the error



Answerd on:2019-08-27 Answerd By:Annaliya

Likes:
Be first to like this answer

Dislikes:
Be first to dislike this answer
Talk about this  Like  Dislike

You might like this video:Watch more here

Watch more videos from this user Here

Learn how to upload a video over here

Yes,

Let's look at an example of how to create and run our first Node js application.

Our application is going to create a simple server module which will listen on port no 7000. If a request is made through the browser on this port no, then server application will send a 'Hello' World' response to the client.


Answerd on:2019-06-22 Answerd By:kethan-vemuri

Likes:
Be first to like this answer

Dislikes:
Be first to dislike this answer
Talk about this  Like  Dislike

You might like this video:Watch more here

Watch more videos from this user Here

Learn how to upload a video over here



Lets together make the web is a better place

We made eduladder by keeping the ideology of building a supermarket of all the educational material available under one roof. We are doing it with the help of individual contributors like you, interns and employees. So the resources you are looking for can be easily available and accessible also with the freedom of remix reuse and reshare our content under the terms of creative commons license with attribution required close.

You can also contribute to our vision of "Helping student to pass any exams" with these.
Answer a question: You can answer the questions not yet answered in eduladder.How to answer a question
Career: Work or do your internship with us.Work with us
Create a video: You can teach anything and everything each video should be less than five minutes should cover the idea less than five min.How to upload a video on eduladder