手机版

nodejs入门教程6: express模块使用示例

时间:2021-09-05 来源:互联网 编辑:宝哥软件园 浏览:

本文说明了nodejs入门教程中express模块的用法。分享给大家参考,如下:

/** *由Dason于2017年3月28日创建。*/var express=require(' express ');var mor gan=require(' mor gan ');//用于打印日志的中间件//创建express var app=express()的实例;/* * *中间件: * connect : node . js *的中间件框架分层处理:每层实现一个功能*使用方法:将特定的中间件传入使用方法*///Express提供内置的中间件express.static来设置静态文件:express.static('静态文件目录')//http://localhost 33603001/test . txt : public相对路径app.use (express.static(')。/public’);//当前项目目录下的文件app . use(mor gan());//当请求到来时,express通过路由控制响应。//1.path方法app.get ('/'),function (req,RES){ RES . end(');});/* * * route * route:根据不同的请求,分配相应的功能*区分:path、request方法*三种路由方法* path * router * route *///2.router方法:是针对同一路由下的多个子路由//http://localhost 33603001/post/add varrouter=//http://localhost 33603001/post/add Router . get('/add ',function(req,RES){ RES . end(' Router/add ');});//http://localhost :3001/post/addrouter . get('/list ',function(req,RES){ RES . end(' Router/list ');});//将定义的路由添加到app的配置中。//第一个参数是基本路径(即请求前的路径),第二个参数是定义的路由app.use('/post ',Router)。//3.路由的路由方法:针对同一路由下的不同请求方法。//http://localhost 33603001/Article App。路线('/文章')。Get (function (req,RES){ RES . end(' route/article get ');}) .post(function(req,RES){ RES . end(' route/article post ');});/* * *路由参数:例如,http://example.com/news/123 * 123是路由参数*第一个参数:指定路由参数名称*第二个参数:函数:* @ parms: next:执行下一个操作;newsId:路由参数*///http://localhost 33603001/news/123 app . param(' news id ',函数(req,RES,next,newsid) {req。newsid=newsid//将值存储在请求对象next()中;});//使用路由参数app.get ('/news/:newsid ',函数(req,RES){ RES . end(' news id 3360 ' req . news id);});//侦听一个端口app.listen (3001,function(){ console . log(' express在http://localhost :3001上运行');})public在项目目录中:

希望本文对nodejs程序的设计有所帮助。

版权声明:nodejs入门教程6: express模块使用示例是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。