ExpressJS入门指南

来源:互联网 发布:java前景如何 编辑:程序博客网 时间:2024/06/04 17:48

ExpressJS入门指南

作者:chszs,转载需注明。博客主页:http://blog.csdn.net/chszs

一、我们创建项目目录。


> 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 lsnpm WARN package.json hello-world@0.0.1 No README.md file found!hello-world@0.0.1 D:\tmp\node\hello-world└─┬ express@3.2.1  ├── buffer-crc32@0.2.1  ├── commander@0.6.1  ├─┬ connect@2.7.7  │ ├── bytes@0.2.0  │ ├── formidable@1.0.13  │ └── pause@0.0.1  ├── cookie@0.0.5  ├── cookie-signature@1.0.1  ├── debug@0.7.2  ├── fresh@0.1.0  ├── methods@0.0.1  ├── mkdirp@0.3.4  ├── qs@0.6.1  ├── range-parser@0.0.4  └─┬ send@0.1.0    └── mime@1.2.6

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

四、创建应用程序


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

// app.jsvar 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()方法,接收同样的参数,比如:

app.listen(3000);console.log('Listening on port 3000');

五、运行程序


现在运行程序,执行命令:
> node app.js

用浏览器访问地址:http://localhost:3000/hello.txt
可以看到输出结果:
Hello World