The best Node.js to create the first application Tutorial In 2024, In this tutorial you can learn Create Node.js applications,Gif examples demonstrate,
If we use PHP to write back-end code, you need Apache or Nginx HTTP server, and accompanied mod_php5 modules and php-cgi.
From this perspective, the entire demand "to receive HTTP requests and provide Web pages" of PHP do not need to deal with.
But for Node.js, a concept completely different. When using Node.js, we not only in the realization of an application, but also realized the whole HTTP server. In fact, our Web application and the corresponding Web server is basically the same.
Before the first application we created Node.js "! Hello, World", let us first understand what Node.js application is made of several parts:
The introduction of required modules: we can use requireinstruction to load Node.js modules.
Create Server: The server can listen for client requests, like Apache, Nginx and other HTTP server.
The serverreceives the request and respond to requests very easy to create, the client can use the browser or terminal sends an HTTP request, the server receives the request and returns a response data.
We userequire instruction to load http module, and instantiate HTTP assigned to the variable http, examples are as follows:
var http = require("http");
Next we use http.createServer () method to create a server, and uses method bindings listen 8888 port. Function by request, response parameters to receive and respond to data.
Examples are as follows, 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) { // 发送 HTTP 头部 // HTTP 状态值: 200 : OK // 内容类型: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // 发送响应数据 "Hello World" 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.
Using thenode command to perform the above code:
node server.js Server running at http://127.0.0.1:8888/
Next, open the browser to access http://127.0.0.1:8888/, you'll see that says "Hello World" page.
Analysis Node.js HTTP server:
Next we show you examples by Gif Pictured actions: