【二】express

一、基本使用

  1. 安装 npm install express --save
  2. 引入 var express = require('express')
  3. 创建你服务器应用程序 var app = express()
  4. 得到路径
app.get('/about', function (req, res) {
	  // 在 Express 中可以直接 req.query 来获取查询字符串参数
	  console.log(req.query)
	  res.send('你好,我是 Express!')
})

5.server.listen

app.listen(3000, function () {
  console.log('app is running at port 3000.')
})

二、express中间件body-parser

在express中没有内置获取表单POST请求体的API,所以需要第三方包

  1. 安装 npm install body-parser -S
  2. 配置
var express = require('express')
var bodyParser = require('body-parser')

var app = express()

//只要加入这个配置,在req请求对象上就会多出来一个属性body,可以直接通过req.body来获取表单POST请求体的数据来了
// parse application/x-www-form-urlencoded 
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})

三、express 静态服务 API

var app = express()
 // 路径带public ( //http://127.0.0.1:3000/public/css/main.css)
app.use('/public/', express.static('./public/'))   
// 将路径中的public替换  ( //http://127.0.0.1:3000/abc/css/main.css)
app.use('/abc/', express.static('./public/'))
// 将路径中的public去掉  ( //http://127.0.0.1:3000/css/main.css)
app.use(express.static('./public/'))

四、Express 中 art-template的使用

npm install --save art-template
npm install --save express-art-template

var express = require('express');
var app = express();

//第一个参数,表示,当渲染以 .art 结尾的文件的时候,使用 art-template 模板引擎
express-art-template 是专门用来在 Express 中把 art-template 整合到 Express 中
//可以把'art'改为html,就可以在html页面中使用模板引擎了

app.engine('art', require('express-art-template'));

//如果想要修改默认的 views 目录,则可以
app.set('view options',render函数的默认路径);

//Express 为 Response 相应对象提供了一个方法:render
app.get('/', function (req, res) {
    res.render('index.art', {
        user: {
            name: 'aui',
            tags: ['art', 'template', 'nodejs']
        }
    });
});

五、页面的重定向

res.send 、res.redirect 这些方法 Express 会自动结束响应

 res.send('Got a DELETE request at /user')
 res.redirect('/')

六、app.js 入门模块的职责

  • 创建服务
  • 做一些服务相关配置
    • 模板引擎
    • body-parser 解析表单 post 请求体
    • 提供静态资源服务
  • 挂载路由
  • 监听端口启动服务

七、Express 提供了一种更好的专门用来包装路由的方式

  • router.js //路由操作
const express = require('express');
// 1. 创建一个路由容器
var router = express.Router()
// 2. 把路由都挂载到 router 路由容器中
router.get('/students',fucntion(req,res){
})

router.get('/students/new',fucntion(req,res){
})
// 3. 把 router 导出
module.exports = router
  • app.js
const router = require('./router');
// 把路由容器挂载到 app 服务中
app.use(router)
  • students.js //数据操作
const fs = require('fs');
const  dbPath = './db.json';
// export.数据操作 = function(){ }

猜你喜欢

转载自blog.csdn.net/weixin_41409254/article/details/83576409
今日推荐