ExpressJS入门实例

  一、我们创建项目目录。

  

复制代码 代码如下:

  > md hello-world

  二、进入此目录,定义项目配置文件package.json。

  为了准确定义,可以使用命令:

  

复制代码 代码如下:

  D:\tmp\node\hello-world> npm info express version

  npm http GET https://registry.npmjs.org/express

  npm http 200 https://registry.npmjs.org/express

  3.2.1

  现在知道ExpressJS框架的最新版本为3.2.1,那么配置文件为:

  

复制代码 代码如下:

  {

  "name": "hello-world",

  "description": "hello world test app",

  "version": "0.0.1",

  "private": true,

  "dependencies": {

  "express": "3.2.1"

  }

  }

  三、使用npm安装项目依赖的包。

  

复制代码 代码如下:

  > npm install

  一旦npm安装依赖包完成,项目根目录下会出现node_modules的子目录。项目配置所需的express包都存放于这里。如果相验证,可以执行命令:

  

复制代码 代码如下:

  > npm ls

  PS D:\tmp\node\hello-world> npm ls

  npm WARN package.json [email protected] No README.md file found!

  [email protected] D:\tmp\node\hello-world

  └─┬ [email protected]

  ├── [email protected]

  ├── [email protected]

  ├─┬ [email protected]

  │ ├── [email protected]

  │ ├── [email protected]

  │ └── [email protected]

  ├── [email protected]

  ├── [email protected]

  ├── [email protected]

  ├── [email protected]

  ├── [email protected]

  ├── [email protected]

  ├── [email protected]

  ├── [email protected]

  └─┬ [email protected]

  └── [email protected]

  此命令显示了express包及其依赖关系。

  四、创建应用程序

  现在开始创建应用程序自身。创建一个名为app.js或server.js的文件,看你喜欢,任选一个。引用express,并使用express()创建一个新应用:

  

复制代码 代码如下:

  // app.js

  var express = require('express');

  var app = express();

  接着,我们可以使用app.动词()定义路由。

  比如使用"GET /"响应"Hello World"字符串,因为res、req都是Node提供的准确的对象,因此你可以调用res.pipe()或req.on('data', callback)或者其它。

  

复制代码 代码如下:

  app.get('/hello.txt', function(req, res){

  var body = 'Hello World';

  res.setHeader('Content-Type', 'text/plain');

  res.setHeader('Content-Length', body.length);

  res.end(body);

  });

  ExpressJS框架提供了更高层的方法,比如res.send(),它可以省去诸如添加Content-Length之类的事情。如下:

  

复制代码 代码如下:

  app.get('/hello.txt', function(req, res){

  res.send('Hello World');

  });

  现在可以绑定和监听端口了,调用app.listen()方法,接收同样的参数,比如:

  五、运行程序

  现在运行程序,执行命令:

  

复制代码 代码如下:

  > node app.js

  用浏览器访问地址:http://localhost:3000/hello.txt

  可以看到输出结果:

  

复制代码 代码如下:

  Hello World