可以从express的角度访问urlExpress搭建一个web服务器varexpresss=require('express');是一个web后端开发框架第三方npm包npmiexpress--savewebserver是一个运行app实例varapp=express();监听端口app.listen(3000)处理路由,会响应不同的地址访问。按模块构建路由,varrouter=express.Router();router.get('/',(req,res)=>{res.send('hello,express');});app.use('/',indexRouter);什么是htmltemplateexpress一些高效的html工具ejs广受欢迎。webserver的核心模式是mvcmodeldata(database)controlcontroller(routing)view(view)html添加view到webserverviews模板文件表示设置目录的地方templateengineuseswhattemplatesyntax<%%>usedforjs语法的嵌入,ejshtml部分是模型数据由router的第二个参数传递render=表示值输出nothingjs语句进行逻辑运算——用于html解析,默认会将html作为文本处理。<%-include('header')%>模板组装语法有利于代码重用中间件从请求到返回,在这个过程中间,通过中间件一个一个完成相应的功能,epress架构思想,pipeline使用中间件app.use()function(err,req,res,next){}第三方中间件next方法如果不使用next,则认为请求结束。res.render()res.end()这些方法也会停止中间件的传播错误处理1让开发者明白什么是错误除外。next(newError())2错误不能直接抛给用户。专门的错误处理中间件app.use(function(err,req,res,naxt){console.log(err.stack)res.status(500).send(somethingbroken))}博客目录分析模型存储数据库文件mroutes存储路由文件Cviews存储模板文件Vpublic存储静态资源index.js程序文件入口文件package.json项目描述作者依赖等Github要代码戳这里。文件路径类型根据不同的请求路径处理不同的响应。实际路径绝对不像.html。他们大概是这样的:varhttp=require('http')varserver=http.createServer()server.on('request',function(req,res){//1.通过req获取当前请求路径。urlvarurl=req.url//2.根据不同的请求路径处理不同的响应if(url==='/'){res.end('indexpage')}elseif(url==='/login'){res.end('登录页面')}elseif(url==='/register'){res.end('注册页面')}else{res.end('404NotFound')}})server.listen(3000,function(){console.log('running...');})浏览器输入http://localhost:3000/registerhttp://localhost:3000http://localhost:3000/登录以到达不同的页面:'+req.url);if(req.url==='/home'||req.url==='/'){res.writeHead(200,{'Content-Type':'text/html'});fs.createReadStream(__dirname+'/index.html','utf8').pipe(res);}elseif(req.url==='/contact'){res.writeHead(200,{'Content-Type':'text/html'});fs.createReadStream(__dirname+'/contact.html','utf8').pipe(res);}elseif(req.url==='/api/users'){varusers=[{name:'AlexZ33',age:26},{name:'jingxin',age:8}];res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(用户));}else{res.writeHead(404,{'Content-Type':'text/html'});fs.createReadStream(__dirname+'/404.html','utf8').pipe(res);}});server.listen(3000,'127.0.0.1');console.log('现在监听3000端口');于是我们打开服务器浏览器,输入http://localhost:3000/home或者http://localhost:3000会访问index.html页面浏览器输入http://localhost:3000/contact}elseif(req.url==='/api/users'){varusers=[{name:'AlexZ33',age:26},{name:'jingxin',age:8}];res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(users));}这个json字符串在实际app中得到的应该是来自于数据库(database)我们输入浏览器中不存在的路径,比如http://localhost:3000/77。处理静态资源路径本质上就是识别。这里有一个关于实现静态资源访问和页面路径设置的小项目。单击此处MVCRESTfulRESTAPI5在几分钟内构建Restful后端REST和RESTFulAPI最佳实践
