扫码一下
查看教程更方便
如果我们使用 php 来编写后端的代码时,需要 apache 或者 nginx 的 http 服务器,并配上 mod_php5 模块和 php-cgi。
从这个角度看,整个"接收 http 请求并提供 web 页面"的需求就不需要 php 来处理。
不过对 node.js 来说,概念完全不一样了。使用 node.js 时,我们不仅仅 在实现一个应用,同时还实现了整个 http 服务器。事实上,我们的 web 应用以及对应的 web 服务器基本上是一样的。
在我们创建 node.js 第一个 "hello, world!" 应用前,让我们先了解下 node.js 应用是由哪几部分组成的:
我们使用 require 指令来载入 http 模块,并将实例化的 http 赋值给变量 http,实例如下:
var http = require("http");
接下来我们使用 http.createserver() 方法创建服务器,并使用 listen 方法绑定 8888 端口。 函数通过 request, response 参数来接收和响应数据。
实例如下,在你项目的根目录下创建一个叫 server.js 的文件,并写入以下代码:
server.js
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/');
以上代码我们完成了一个可以工作的 http 服务器。
使用 node 命令执行以上的代码:
$ node server.js
server running at http://127.0.0.1:8888/
接下来,打开浏览器访问 http://127.0.0.1:8888/
, 你会看到一个写着 "hello world"的网页。
分析node.js 的 http 服务器: