nodejs入門教程六:express模塊用法示例
更新時間:2017年04月24日 11:50:07 作者:Dason_yu
這篇文章主要介紹了nodejs入門教程之express模塊用法,結合實例形式分析了express模塊的功能、創(chuàng)建、路由相關使用技巧,需要的朋友可以參考下
本文實例講述了nodejs入門教程之express模塊用法。分享給大家供大家參考,具體如下:
/**
* Created by Dason on 2017/3/28.
*/
var express = require('express');
var morgan = require('morgan');//打印日志的中間件
//創(chuàng)建express 的實例
var app = express();
/**
* 中間件:
* Connect: Node.js的中間件框架
* 分層處理:每層實現一個功能
* 使用 use方法:向use方法傳入具體的中間件
*/
//Express 提供了內置的中間件 express.static 來設置靜態(tài)文件:express.static('靜態(tài)文件的目錄')
//http://localhost:3001/test.txt: public的相對路徑
app.use(express.static('./public'));//當前項目目錄下的文件
app.use(morgan());
// 當請求過來時,express通過路由來控制做出響應
//1. 路由的path 方法
app.get('/',function(req,res){
res.end('');
});
/**
* 路由
* 路由:根據不同的請求,分配相應的函數
* 區(qū)分:路徑、請求方法
* 三種路由方法
* 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:執(zhí)行下一步操作;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);
});
//監(jiān)聽一個端口
app.listen(3001,function(){
console.log('express running on http://localhost:3001');
})
public在項目目錄下:

希望本文所述對大家nodejs程序設計有所幫助。
相關文章
Node?文件查找優(yōu)先級及?Require?方法文件查找策略
這篇文章主要介紹了Node文件查找優(yōu)先級及Require方法文件查找策略。文章圍繞主題展開詳細的內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09
通過node-mysql搭建Windows+Node.js+MySQL環(huán)境的教程
這篇文章主要介紹了通過node-mysql搭建Windows+Node.js+MySQL環(huán)境的教程,node-mysql是JavaScript編寫的一個Node的MySQL驅動,需要的朋友可以參考下2016-03-03

