Before we create the first "Hello, world!" app for node. JS, let's start by understanding which parts of the node. JS application are composed:
introducing the required module: We can use the require directive to load the node. JS module.
Create server: The server can listen to the client's request, similar to Apache, Nginx and other HTTP server.
receiving requests and responding to the request server is easy to create, and the client can send HTTP requests using a browser or terminal, and the server returns the response data after receiving the request.
Introducing the required module
We use the require directive to load the HTTP module and assign the instantiated HTTP value to the variable HTTP, as shown in the following example:
var http = require ("http");
Creating a server
Next we use the Http.createserver () method to create the server and bind port 8888 using the Listen method. The function receives and responds to data through the request, response parameter.
As an example, create a file called Server.js in the root directory of your project and write the following code:
var http = require (' http '); Http.createserver (function (request, response) { //Send HTTP Header //HTTP status value: 200:ok
//content Type: Text/plain response.writehead ($, {' Content-type ': ' Text/plain '}); Send the response data "Hello World" response.end (' Hello world\n ');}). Listen (8888);//terminal print the following information Console.log (' Server running at http://127.0.0.1:8888/');
The above code we have completed a working HTTP server.
Use the node command to execute the above code:
Node Server.jsserver running at http://127.0.0.1:8888/
Parsing the HTTP Server for node. JS:
- The first line requests (require) node. js's own HTTP module and assigns it to the HTTP variable.
- Next we invoke the function provided by the HTTP module: Createserver. This function returns an object that has a method called Listen, which has a numeric parameter that specifies the port number that the HTTP server listens on.
node. JS creates the first app