node. JS creates an HTTP server (tested, this article is a reliable t_t)

Source: Internet
Author: User
Tags node server

node. JS creates an HTTP server

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.

The underlying HTTP server

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) {  Response.writehead ($, {' Content-type ': ' Text/plain '});  Response.End (' Hello world\n ');}). Listen (8888); 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/

See here is simply excited no language table, finally an article does not hang dad, and then stepped on countless pits

Next, open the browser to access http://127.0.0.1:8888/, and you'll see a page with "Hello World".

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 an HTTP server (tested, this article is a reliable t_t)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.