Objective:
If we use PHP to write back-end code, we need an Apache or Nginx http server, with MOD_PHP5 modules and php-cgi.
From this perspective, the entire "Receive HTTP request and provide WEB page" requirement does not need PHP to handle at all.
But for node. JS, the concept is completely different. When using node. js, we are not only implementing an application, but also implementing an entire HTTP server.
In fact, our web application and the corresponding Web server are basically the same.
To create a simple HTTP server:
Here we create this instance by creating a file and then executing it in the same way.
Under the E:\NodejsDemo folder, create a "server.js" file with the following code:
1 var http = require ("http"); 2 3 http.createserver (function(request,response) {4 response.writehead (200 , {"Content-type": "Text/plain"}); 5 Response.End ("Hello world!\n"); 6 }). Listen (n); 7 8 console.log ("Server running at http://127.0.0.1:88/")
With the above code, we have completed the creation of a simple node. js http Server.
Below we use the node command under DOS to run it:
At this point, the firewall may prompt, click Allow access:
Then, we open the browser, Access address: http://127.0.0.1:88, the effect is as follows:
See this interface, is not very chicken frozen, haha.
Simple parsing of node. JS HTTP Server:
Here, I flatter a simple introduction to the main, so do not do too much introduction, we understand the good.
The official interpretation of the website is as follows:
- 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.
Personal Introduction:
- Require represents the introduction of a module, where we introduce the HTTP module of the system, creating an HTTP module service.
- We then saved it to an HTTP object.
- Below, we use the Createserver method of the object to execute a function.
- The function passes in a request and a response object of response, sets the response status code to 200, the response type is text, and the response is "Hello world! ”。
- Finally, call its "Listen" method, start listening, listening port is 88.
- At the end of the command, we output a log: "Server running at http://127.0.0.1:88".
Summary:
I also just learned, so deep experience, this thing slowly understand, not too merely grammar. Gradual and progressive.
I hope you get started quickly, hehe.
node. JS Tutorial 03-Creating an HTTP server