In this section, we will show you how to build a simple node. js HTTP Server from a beginner's perspective
Create Myfirsthttpserver.js
Lets require/import the http Modulevar http = require (' http ');//lets define a port we want to listen toconst port=8080; We need a function which handles requests and send Responsefunction HandleRequest (request, Response) { Response.End ( ' It works!! Path hit: ' + Request.url);} Create a Servervar server = Http.createserver (handlerequest);//lets start our Serverserver.listen (PORT, function () { C1/>//callback triggered when the server is successfully listening. hurray! Console.log ("Server listening on:http://localhost:%s", PORT);});
To run a file using node
> Node Myfirsthttpserver.js#outputserver listening on:http://localhost:8080
The above has been opened on the browser http://localhost:8080
Analysis:
Lets require/import the http Modulevar http = require (' http ');
node. JS has a core module for wearing a http/https, so we just need to introduce an HTTP module to create an HTTP server
// We need a function which handles requests and send response function HandleRequest (request, Response) { Response.End (' + Request.url);}
We need a function to handle all requests and responses.
The above code is the entry point for your server project (i.e. you can respond to requests based on your business logic)
// Create a server var server = http.createserver (handlerequest); // Lets start our server Server.listen (PORT, function () { ///Callback triggered when the server is successfully listening. hurray! Console.log ("Server listening on:http://localhost:%s", PORT);});
Above, create a suction of the HTTP server object and ask it to listen to a port
The Createserver method is used to create a new server instance and use the listener function as a parameter
We can then invoke a function that listens on the server to start the server
The above is the basic HTTP server running
Now let's add some real needs
For different URL paths, your server should have a different response
Which means we need a dispatcher.
Dispatcher is a route (router) that you can use to invoke the request handler code you want to invoke when targeting a different URL path.
First: Install the Dispatcher module
There are many different modules, for example, we have installed the basic module
> NPM Install Httpdispatcher
Note: NMP is a package manager that provides core open source modules for JS and Nodejs. We use the ' npm Install ' command to install all required modules
Below, use the Dispatcher module
var dispatcher = require (' Httpdispatcher ');
Next, let dispatcher run in the listener function.
// Lets Use our Dispatcher function HandleRequest (request, Response) { try { //log the request On console console.log (request.url); // Disptach Dispatcher.dispatch (request, response); Catch (Err) { console.log (err); }}
Let's define some routes
Routing defines what the server should do when the browser requests a specially-made URL
//For all your static (js/css/images/etc.) Set the directory name (relative path).Dispatcher.setstatic ('Resources');//A Sample GET RequestDispatcher.onget ("/page1", Function (req, res) {Res.writehead ( $, {'Content-type':'Text/plain'}); Res.end ('Page One');}); //A Sample POST RequestDispatcher.onpost ("/post1", Function (req, res) {Res.writehead ( $, {'Content-type':'Text/plain'}); Res.end ('Got Post Data');});
Now let's try a different address:
- Get/page1 = ' Page One '
- Post/page2 = ' Page '
- Get/page3 = 404
- Get/resources/images-that-exists.png = Image Resource
- Get/resources/images-that-does-not-exists.png = 404
You can make a GET request by entering a URL in the browser's address bar. For post requests, you can use the Postman tool
Ok! You can now build a simple HTTP server and make it run!
Above we created a basic HTTP server, which was created by using an HTTP module and a simple dispatcher module, Displatcher is used to allocate (dispatch) HTTP requests to the appropriate route.
Build your first HTTP server in node. js