ExpressJS入门指南

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

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

五、运行程序


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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值