nodejs创建第一个应用

node.js 创建第一个应用

如果我们使用php来编写后端的代码时,需要apache 或者 nginx 的http 服务器,并配上 mod_php5 模块和php-cgi。

从这个角度看,整个”接收 http 请求并提供 web 页面”的需求根本不需 要 php 来处理。

不过对 node.js 来说,概念完全不一样了。使用 node.js 时,我们不仅仅 在实现一个应用,同时还实现了整个 http 服务器。事实上,我们的 web 应用以及对应的 web 服务器基本上是一样的。

在我们创建 node.js 第一个 “hello, world!” 应用前,让我们先了解下 node.js 应用是由哪几部分组成的:

引入 required 模块:我们可以使用 require 指令来载入 node.js 模块。

创建服务器:服务器可以监听客户端的请求,类似于 apache 、nginx 等 http 服务器。

接收请求与响应请求 服务器很容易创建,客户端可以使用浏览器或终端发送 http 请求,服务器接收请求后返回响应数据。

创建 node.js 应用

步骤一、引入 required 模块

我们使用 require 指令来载入 http 模块,并将实例化的 http 赋值给变量 http,实例如下:

var http =require(“http”);

步骤一、创建服务器

接下来我们使用 http.createserver() 方法创建服务器,并使用 listen 方法绑定 8888 端口。 函数通过 request, response 参数来接收和响应数据。

实例如下,在你项目的根目录下创建一个叫 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/

nodejs 创建第一个应用

接下来,打开浏览器访问 http://127.0.0.1:8888/,你会看到一个写着 “hello world”的网页。

‘).addclass(‘pre-numbering’).hide();
$(this).addclass(‘has-numbering’).parent().append($numbering);
for (i = 1; i

Posted in 未分类

发表评论