- 导入需要模块: 我们使用require指令加载Node.js模块。
- 创建服务器: 服务器将监听类似Apache HTTP Server客户端的请求。
- 读取请求,并返回响应: 在前面的步骤中创建的服务器将读取客户端发出的HTTP请求,它可以从一个浏览器或控制台并返回响应。
创建Node.js应用 步骤 1 - 导入所需的模块
我们使用require指令来加载HTTP模块和存储返回HTTP,例如HTTP变量,如下所示:
引用
var http = require("http");
步骤 2: 创建服务
在接下来的步骤中,我们使用HTTP创建实例,并调用http.createServer()方法来创建服务器实例,然后使用服务器实例监听相关联的方法,把它绑定在端口8081。 通过它使用参数的请求和响应函数。编写示例实现返回 "Hello World".
引用
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
上面的代码创建监听即HTTP服务器。在本地计算机上的8081端口等到请求。
步骤 3: 测试请求和响应
让我们把步骤1和2写到一个名为main.js的文件,并开始启动HTTP服务器,如下所示:
引用
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(8081);
// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');
现在执行main.js来启动服务器,如下:
$ node main.js
验证输出。服务器已经启动
Server running at http://127.0.0.1:8081/
发出Node.js服务器的一个请求
在任何浏览器中打开地址:http://127.0.0.1:8081/,看看下面的结果。
First Application
恭喜,第一个HTTP服务器运行并响应所有的HTTP请求在端口8081。