您好,登錄后才能下訂單哦!
本文實(shí)例講述了nodejs入門(mén)教程之express模塊用法。分享給大家供大家參考,具體如下:
/** * Created by Dason on 2017/3/28. */ var express = require('express'); var morgan = require('morgan');//打印日志的中間件 //創(chuàng)建express 的實(shí)例 var app = express(); /** * 中間件: * Connect: Node.js的中間件框架 * 分層處理:每層實(shí)現(xiàn)一個(gè)功能 * 使用 use方法:向use方法傳入具體的中間件 */ //Express 提供了內(nèi)置的中間件 express.static 來(lái)設(shè)置靜態(tài)文件:express.static('靜態(tài)文件的目錄') //http://localhost:3001/test.txt: public的相對(duì)路徑 app.use(express.static('./public'));//當(dāng)前項(xiàng)目目錄下的文件 app.use(morgan()); // 當(dāng)請(qǐng)求過(guò)來(lái)時(shí),express通過(guò)路由來(lái)控制做出響應(yīng) //1. 路由的path 方法 app.get('/',function(req,res){ res.end(''); }); /** * 路由 * 路由:根據(jù)不同的請(qǐng)求,分配相應(yīng)的函數(shù) * 區(qū)分:路徑、請(qǐng)求方法 * 三種路由方法 * path * router * route */ //2.router 方法: 針對(duì)同一個(gè)路由下的多個(gè)子路由 // 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的配置中 //第一個(gè)參數(shù):基礎(chǔ)路徑(即請(qǐng)求前的路徑),第二個(gè)參數(shù):定義的路由 app.use('/post',Router); //3. 路由的route 方法:針對(duì)同一個(gè)路由下的不同請(qǐng)求方法 //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'); }); /** * 路由參數(shù):例如 http://example.com/news/123 * 123 就是路由參數(shù) * 第一個(gè)參數(shù):指定路由參數(shù)名字 * 第二個(gè)參數(shù):function: * @parms:next:執(zhí)行下一步操作;newsId:路由參數(shù)的值 */ //http://localhost:3001/news/123 app.param('newsId',function(req,res,next,newsId){ req.newsId = newsId;//將值存儲(chǔ)到請(qǐng)求對(duì)象中 next(); }); //使用該路由參數(shù) app.get('/news/:newsId',function(req,res){ res.end('newsId:' + req.newsId); }); //監(jiān)聽(tīng)一個(gè)端口 app.listen(3001,function(){ console.log('express running on http://localhost:3001'); })
public在項(xiàng)目目錄下:
希望本文所述對(duì)大家nodejs程序設(shè)計(jì)有所幫助。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。