使用express创建web服务器

使用express创建web服务器
laiqun@msn.cn

Contents

1. 简单的express服务器

安装npm install express使用npm找不到源,改用cnpm

第一版本

var express = require('express');
var app = express();
app.listen(18001,function afterlisten(){
console.log('express running on http://localhost:18001');
}
);

运行后,在浏览器打开localhost:18001 提示不能GET /

解决方法加入路由

var express = require('express');
var app = express();
app.get('/',function(req,res){
res.end('hello\n');
});
app.listen(18001,function afterlisten(){
console.log('express running on http://localhost:18001');
}
);

运行后,在浏览器打开localhost:18001返回hello * 除了手写,express还提供了生成工具,

先来安装 npm install -g express-generator 如何使用 express 你的项目名字,会产生了一个目录

执行文件在bin目录下 无法运行 ,需要安装必须的包 npm install


2. 静态文件服务

使用静态文件中间件

var express = require('express');
var app = express();
app.use(express.static('public'));//public 为静态文件目录
app.get('/',function(req,res){
res.end('hello\n');
});
app.listen(18001,function afterlisten(){
console.log('express running on http://localhost:18001');
}
);

创建静态文件 mkdir public vim public/test.txt 写入hello world

然后 使用curl http://localhost:180001/text.txt即可访问


3. 路由

分析URL: 协议 域名 目录 文件参数 http://www.baidu.com/doc/hello.txt?source=chrome&from=xxx 分析URL: 协议 域名 目录 文件参数 http://www.baidu.com/doc/hello.txt#xx xx为锚点或js路由 路由的含义 :没有扩展名的URL 不是映射到某个文件,而是主机名目录,并不是文件,可能是个处理函数 区分:路径 请求方法 来交给不同的函数

三种方法

  1. path app.动词

    例如 app.get

  2. Router 例如

    var Router = express.Router();
    /** http://example.com/post/add* http://example.com/post/list* 存在公共前缀,最好用router来组织 */
    Router.get('/add',function(req,res){
    res.end('Router /add\n');
    });
    Router.get('lsit',funciton(req,res){
    res.end('Router /list\n');
    });
    app.use('/post',Router);//第一个参数指定基础路由为post
  3. route方式 针对一个路由下不同方法的处理

app.route('/article')
.get(function(req,res){
res.end('route /article get\n');
})
.post(function(req,res){
res.end('route /article get\n');
});
//测试 curl -POST htpp://localhost:180001/article

路由参数

//http://example.com/new/123
app.param('newId',function(req,res,next,newsId){
req.newsId = newsId;//URL参数中的值
next();//执行完之后调用的,即使返回给了用户数据,也会执行//打印请求日志 morgan });
app.get('/news/:newsId',function(req,jres){
res.end('newsId: '+req.newsId+'\n');
})

4. 中间件

基于Connect。分层处理。每层使用一个功能

 
上一篇:Python之路:常用算法与设计模式


下一篇:A1049. Counting Ones