您的位置:首页 > Web前端 > Node.js

Node.js —— 使用express模块创建静态web服务器及其路由

2017-11-24 14:33 1131 查看
1、使用express创建静态web服务器

首先使用命令行在当前路径创建目录public(可自定义),并在目录下创建文件test.txt(可自定义)

$ mkdir public
$ vim test.txt //(文件内容自定义)


在 node.js 文件中指定静态目录(./public是静态目录)

app.use(express.static("./public"));


通过命令行访问静态目录下的静态文件(“/test.txt”是静态目录下的文件的相对路径)

$ curl http://localhost:18001/test.txt


2、路由的创建方法

路由:将不同的请求,分配给相应的处理函数

(1)path 方法,即直接填入路由的相对路径

app.get('/add',function(req,res){
res.end('path /add\n');
})


命令行下执行

$ curl http://localhost:18001/add[/code] 
(2)路由的Router方法,用于创建在一个路由下的多个子路由

var Router=express.Router();

Router.get('/add',function(req,res){
res.end('Router /add\n');
});// 创建子路由add

Router.get('/list',function(req,res){
res.end('Router /list\n');
});// 创建子路由list

app.use('/post',Router);// post是主路由


命令行下执行

$ curl http://localhost:18001/post/add) $ curl http://localhost:18001/post/list)[/code] 
(3)路由的route方式,用于创建一个路由在不同方法下的不同处理

app.route('/article')
.get(function(req,res){
res.end("route /article get\n");
})// 对get方法的处理

.post(function(req,res){
res.end("route /article post\n");
});// 对post方法的处理


命令行下执行(-X用于指定方法,若不指定,默认为GET)

$ curl -X POST http://localhost:18001/article $ curl -X GET http://localhost:18001/article


3、路由参数的使用

创建路由参数

语法:app.param( name,function ),name是路由参数的名字,function是路由参数的处理函数

app.param('newsId',function(req,res,next,newsId){
req.newsId=newsId;
next();
});


使用路由参数

app.get('/news/:newsId',function(req,res){
res.end("newsId:"+req.newsId+"\n");
});


命令行下输入

$ curl http://localhost:18001/news/123


完整代码:

var express=require("express");
var app=express();

// 使用express创建静态服务器
app.use(express.static("./public"));

// 路由的path方法,即直接填入文件路径
app.get('/add',function(req,res){ res.end('path /add\n'); })

// 路由的Router方法
var Router=express.Router();
Router.get('/add',function(req,res){
res.end('Router /add\n');
});
Router.get('/list',function(req,res){
res.end('Router /list\n');
});
app.use('/post',Router);

// 路由的route方式
app.route('/article')
.get(function(req,res){
res.end("route /article get\n");
})
.post(function(req,res){
res.end("route /article post\n");
});

// 路由参数
app.param('newsId',function(req,res,next,newsId){ req.newsId=newsId; next(); });
app.get('/news/:newsId',function(req,res){
res.end("newsId:"+req.newsId+"\n");

});

app.listen(18001,function afterListen(){
console.log("express running on http://localhost:18001"); });


4、使用express模板

1、安装express-generator

npm install -g express-generator


2、在当前文件夹中,创建 express 项目

express [项目名称]


3、进入 express 项目,并安装相关依赖包

cd [express项目的路径]
npm install


4、执行express项目(express的执行脚本是bin/www)

node bin/www


5、关于中间件

1、connect:node.js的中间件框架

2、分层处理

3、每层实现一个功能

4、预处理中间件

5、后置处理中间件

// 后置处理中间件
ResellerSchema.post('save',function (next) {
console.log('this is ResellerSchema post save middleware');
next();
});
// 预处理中间件
ResellerSchema.pre('save',function (next) {
console.log('this is ResellerSchema pre save middleware');
next();
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息