Express是什么

  • Express 是一个放弃最小规模的灵便的 Node.js Web 利用程序开发框架,为 Web 和挪动应用程序提供一组弱小的性能。
  • 应用您所抉择的各种 HTTP 实用工具和中间件,疾速不便地创立弱小的 API。
  • Express 提供精简的根本 Web 应用程序性能,而不会暗藏您理解和青眼的 Node.js 性能。
  • 中文地址:https://www.expressjs.com.cn/

应用

下载

npm i express --save

构建指定文件

// index.js 举例,另外 `.js` 能够省略node index.js

批改完代码主动构建

  • nodemon: 第三方插件,就是为了解决 node 每次批改实现当前都须要从新构建的问题
  • 下载:npm i nodemon -g,这种工具类的最好都是全局装置
  • 应用形式:nodemon index.js

API

hello world
var express = require('express')// 创立服务器,相当于http.createServervar app = express();app.get('/', function(req,res) {    res.send('hello')})app.listen(9527,function() {    console.log('app is running at port 9527')})
根本路由
// getapp.get('/', function(req,res) {    res.send('get')})// postapp.post('/', function(req,res) {    res.send('post')})
动态服务
// 公开指定目录// 只有这样做了,你就能够间接通过/public/xx的形式拜访public下的所有资源了app.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'))       // 通过localhost:9527/abc/index.html
Express中应用art-template

装置:

npm i --save art-templatenpm i --save express-art-template

配置:

/*    第一个参数示意当渲染以 .art 结尾的文件的时候,应用 art-template 引擎。当然你能够不应用 .art    这里配置是啥,上面的render中就要应用啥    咱们在下载以来的时候,下载了 express-art-template 和 art-template,然而咱们并没有引入应用,是因为前者应用了后者*/// app.engine('art', require('express-art-template'))app.engine('html', require('express-art-template'))

应用:

/*    express 为 response(res) 这个响应对象提供了一个办法:render    不过 render 默认是不能应用的,然而如果配置了 art-template 模板引擎就能够应用了    res.render('html模板名',{模板数据})    第一个参数不能写门路,默认会去我的项目中的views目录中查找该模板文件,即所有视图文件都默认放在views目录中    当然也是能够更改默认门路的,批改形式是app.set('views','pages')。把默认门路从views批改为pages*/app.get('/',function(req,res) {    console.log(req.query)    // res.render('index.art')    res.render('index.html',{         title: "你号啊"    })})
Express中应用post申请

Express 中没有内置解析Psot申请体的API,所需须要应用第三方的包 body-parser

装置:

npm i --save body-parser

配置:

const express = require('express')// 引入中间件,用来解析Post申请const bodyParser = require('body-parser')const app = express()/*    配置 body-parser (中间件,专门用来解析 Post申请体)    只有退出这个配置,则在 req 申请对象上就多了一个 body 属性    也就是说,咱们能够间接应用 req.body 来获取 Post 申请体重的数据了*/// parser application/x-www.form-urlencodedapp.use(bodyParser.urlencoded({extended: false}))// parser application/jsonapp.use(bodyParser.json())app.post('/',function(req,res) {    console.log(req.body)})app.listen('9530',function() {    console.log('running at port localhost:9530')})