参考文档:http://javascript.ruanyifeng.com/nodejs/express.html
Express 是目前最流行的基于 Node.js 的 Web 开发框架,可以快速地搭建一个完整功能的网站。
创建测试项目
mkdir hello-world
进入该目录,新建一个 package.json 文件,内容如下。
1 2 3 4 5 6 7 8 9 10
| { "name": "hello-world", "description": "hello world test app", "version": "0.0.1", "private": true, "dependencies": { "express": "4.x" } }
|
安装 express
npm install
执行上面的命令以后,在项目根目录下,新建一个启动文件,假定叫做 index.js。
1 2 3 4 5 6
| var express = require('express'); var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);
|
运行启动脚本
node index
访问 http://localhost:8080
它会在浏览器中打开当前目录的 public 子目录(严格来说,是打开 public 目录的 index.html 文件)。如果 public 目录之中有一个图片文件 my_image.png,那么可以用 http://localhost:8080/my_image.png 访问该文件。
目录结构

执行结果

也可以 http://localhost:8080/WX.jpeg
也可以生成动态网页
express 1 2 3 4 5
| var app = express(); app.get('/', function (req, res) { res.send('Hello world!'); }); app.listen(3000);
|
运行启动脚本
node index

启动脚本 index.js 的 app.get 方法,用于指定不同的访问路径所对应的回调函数,这叫做 “路由”(routing)。上面代码只指定了根目录的回调函数,因此只有一个路由记录。实际应用中,可能有多个路由记录。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| 比如: var express = require('express'); var app = express();
app.get('/', function (req, res) { res.send('Hello world!'); }); app.get('/customer', function(req, res){ res.send('customer page'); }); app.get('/admin', function(req, res){ res.send('admin page'); });
app.listen(3000);
|
比较庞大的时候可以单独存放
eg:
1 2 3 4 5 6 7 8 9 10 11 12 13
| // routes/index.js
module.exports = function (app) { app.get('/', function (req, res) { res.send('Hello world'); }); app.get('/customer', function(req, res){ res.send('customer page'); }); app.get('/admin', function(req, res){ res.send('admin page'); }); };
|
原先的 index 引入
1 2 3 4 5
| // index.js var express = require('express'); var app = express(); var routes = require('./routes')(app); app.listen(3000);
|