什么是Express?Express是一个灵活的Node.jsWeb应用程序开发框架,保持最小化,为Web和移动应用程序提供一组强大的功能。使用您选择的各种HTTP实用程序和中间件快速轻松地创建强大的API。Express提供精简的基本Web应用程序功能,而不会隐藏您熟悉和喜爱的Node.js功能。中文地址:https://www.expressjs.com.cn/使用下载npmiexpress--save构建指定文件//index.js例如,.js可以省略nodeindex.js自动修改代码后构建nodemon:第三方插件是为了解决每次修改后需要重新构建node的问题。下载:npminodemon-g。这种工具最好全局安装:nodemonindex.jsAPIhelloworldvarexpress=require('express')//创建服务器,相当于http.createServervarapp=express();app.get('/',function(req,res){res.send('hello')})app.listen(9527,function(){console.log('appisrunningatport9527')})基本路由//getapp.get('/',function(req,res){res.send('get')})//postapp.post('/',function(req,res){res.send('post')})静态服务//公开指定目录//一旦你这样做,你可以直接通过/public/xxApp.use('/public',express.static('./public'))//通过localhost:9527/public/index.html//第一个参数也可以省略,但是当省略第一个参数时,访问方法中相应的路径也要省略app.use(express.static('./static'))//的访问方式变为localhost:9527/index.html//还有一种方法是给公共目录取别名app.use('/abc',express.static('./pages'))//在Express中使用art-templavia本地主机:9527/abc/index.html安装:npmi--saveart-templatenpmi--saveexpress-art-templateconfiguration:/*第一个参数表示渲染以.art结尾的文件时,使用art-template引擎当然可以不使用.art这里的配置是什么,后面的render会用到什么?我们下载了express-art-template和art-template,但是我们没有介绍和使用,因为前者使用的是后者*///app.engine('art',require('express-art-template'))app.engine('html',require('express-art-template'))use:/*expressforresponse(res)这个响应对象提供了一个方法:render,但是默认不能使用render,但是如果配置了art-template模板引擎就可以使用。res.render('html模板名称',{模板数据})第一个参数不能写路径。默认情况下,它会在项目的views目录下寻找模板文件,即所有视图文件默认都放在views目录下。当然,默认路径也是可以更改的。修改方法为app.set('views','pages')。将默认路径从视图更改为页面*/app.get('/',function(req,res){console.log(req.query)//res.render('index.art')res.render('index.html',{title:"Yournumber"})})Express使用post请求。Express没有用于解析Psot请求正文的内置API。需要使用第三方包body-parser安装:npmi--savebody-parser配置:constexpress=require('express')//引入中间件解析Post请求constbodyParser=require('body-parser')constapp=express()/*配置body-parser(中间件,专门用来解析Post请求body)只要加上这个配置,req请求对象上就会多一个body属性。也就是说,我们可以直接使用req.body获取Post请求权重的数据*///parserapplication/x-www.form-urlencodedapp.use(bodyParser.urlencoded({extended:false}))//解析器application/jsonapp.use(bodyParser.json())app.post('/',function(req,res){console.log(req.body)})app.listen('9530',function(){console.log('运行在端口localhost:9530')})
