NodeJS has an HTTP server built in for debugging. The first step to learning any new language or technology is to write a Hello World Program. paste the code below. First, create a file named app. js with the following content:
// App. jsvar http = require ('http'); http. createServer (function (req, res) {res. writeHead (200, {'content-type': 'text/html'}); res. write ('
Next, open the command line tool, run the node app. js command, and open the browser to access http: // 127.0.0.1: 3000. The following content is displayed:
The simplest HTTP server implemented with Node. js is born. The above program has done several things:
(1) The program calls the http module provided by Node. js and uses this module to create an HTTP event listener. The listening port is 3000, which can be set by itself;
(2) write the response header and body in the response event of the listener;
(3) When you access http: // 127.0.0.1: 3000 in a browser, the listener returns a response.
The HTTP service does not exit immediately after it ends like Hello World, but waits until Ctrl + C or Ctrl + Break is pressed. This is because the event listener is created in the listen function, so that the Node. js process does not exit the event loop.