栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

nodejs入门教程六:express模块用法示例

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

nodejs入门教程六:express模块用法示例

本文实例讲述了nodejs入门教程之express模块用法。分享给大家供大家参考,具体如下:


var express = require('express');
var morgan = require('morgan');//打印日志的中间件
//创建express 的实例
var app = express();

//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('');
});

//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://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在项目目录下:

希望本文所述对大家nodejs程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/88190.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号