nodjs(六) express模块

/**
 * Created by Dason on 2017/3/28.
 */
var express = require('express');
var morgan = require('morgan');//打印日志的中间件
//创建express 的实例
var app = express();

/**
 * 中间件:
 * Connect: Node.js的中间件框架
 * 分层处理:每层实现一个功能
 * 使用 use方法:向use方法传入具体的中间件
 */
//Express 提供了内置的中间件 express.static 来设置静态文件:express.static('静态文件的目录')
//http://localhost:3001/test.txt: public的相对路径
app.use(express.static('./public'));//当前项目目录下的文件

app.use(morgan());


// 当请求过来时,express通过路由来控制做出响应
//1. 路由的path 方法
app.get('/',function(req,res){
    res.end('');
});

/**
 * 路由
 * 路由:根据不同的请求,分配相应的函数
 * 区分:路径、请求方法
 * 三种路由方法
 * path
 * router
 * route
 */

//2.router 方法: 针对同一个路由下的多个子路由
// http://localhost:3001/post/add
var Router = express.Router();

// http://localhost:3001/post/add
Router.get('/add',function(req,res){
    res.end('Router /add');
});

// http://localhost:3001/post/add
Router.get('/list',function(req,res){
    res.end('Router /list');
});

//将定义的路由加入到 app的配置中
//第一个参数:基础路径(即请求前的路径),第二个参数:定义的路由
app.use('/post',Router);

//3. 路由的route 方法:针对同一个路由下的不同请求方法
//http://localhost:3001/article
app.route('/article')
    .get(function(req,res){
        res.end('route /article get');
    })
    .post(function(req,res){
        res.end('route /article post');
    });


/**
 * 路由参数:例如 http://example.com/news/123
 * 123 就是路由参数
 * 第一个参数:指定路由参数名字
 * 第二个参数:function:
 *      @parms:next:执行下一步操作;newsId:路由参数的值
 */

//http://localhost:3001/news/123
app.param('newsId',function(req,res,next,newsId){
    req.newsId = newsId;//将值存储到请求对象中
    next();
});
//使用该路由参数
app.get('/news/:newsId',function(req,res){
    res.end('newsId:' + req.newsId);
});


//监听一个端口
app.listen(3001,function(){
    console.log('express running on http://localhost:3001');
})


public在项目目录下:




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值