Express入门

1、请求与响应

const express = require('express')

var app = express();

app.get('/', function(req, res) {
  res.end('hello')
})

app.listen(3000)

console.log( 'server listening to 3000, http://localhost:3000' )

具体的API可以查看:http://www.expressjs.com.cn/4x/api.html#req.query

nodemon:一个可以监听文件修改,自动重启node服务的插件。

只需要全局安装,使用nodemon server命令,会自动查找当前目录的server.js

2、路由参数(动态路由)

const express = require('express')

var app = express();

app.get('/profile/:id/user/:name', function (req, res) {
  console.log(req.params) //获取有所动态路由的id
  res.end(`id=${req.params.id}`)
})

app.listen(3000)

console.log( 'server listening to 3000, http://localhost:3000' )

路由可以使用正则表达式

3、查询字符串

const express = require('express')

var app = express();

app.get('/', function(req, res) {
  console.log(req.query)  //通过req.query获取?a=1
  res.end('hello')
})

app.listen(3000)

console.log( 'server listening to 3000, http://localhost:3000' )

4、解析POST参数

解析post请求参数需要借助body-parse中间件,安装这个中间件。

解析Form Data数据

这种方式的请求Content-Type: 'application/x-www-form-urlencoded'

这种是form表单提交过来的数据,用法./server.js

const path = require('path')
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser')

var app = express();
/**[解析form提交过来的数据] */
app.use(bodyParser.urlencoded({ extended: false }))

app.post('/login', function(req, res) {
  // [这里接收传递过来的参数]
  console.log( req.body )
  res.send('ok')
})

app.listen(3000)

console.log( 'server listening to 3000, http://localhost:3000' )

解析Request Paylod数据

这种请求方式的Content-Type: 'application/json;charset=UTF-8'

使用ajax或者fetch传递过来的json./server.js

const path = require('path')
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser')

var app = express();

/**[解析ajax或者fetch传递过来的json] */
app.use(bodyParser.json())

app.post('/login', function(req, res) {
  // [这里接收传递过来的参数]
  console.log( req.body )
  res.send('ok')
})

app.listen(3000)

console.log( 'server listening to 3000, http://localhost:3000' )

解析2种参数

const path = require('path')
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser')

var app = express();

const bodyAjax = bodyParser.json()
const bodyForm = bodyParser.urlencoded({ extended: false })

app.post('/login_form',bodyForm, function(req, res) {
  // [这里接收传递过来的参数]
  console.log( req.body , 'bodyForm')
  res.send('ok')
})

app.post('/login_ajax', bodyAjax, function(req, res) {
  // [这里接收传递过来的参数]
  console.log( req.body , 'bodyAjax')
  res.send('ok')
})

app.listen(3000)

console.log( 'server listening to 3000, http://localhost:3000' )

5、上传文件

安装处理文件程序:multer

./index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <h1>hello world</h1>

  <form action="/upload" enctype="multipart/form-data" method="POST">
      <h2>图片上传</h2>
      <input type="file" name="logo" accept=".png,.jpg,.jpeg">
    <input type="submit" value="提交">
  </form>

</body>
</html>

./server.js

const path = require('path')
const fs = require('fs')
const express = require('express')
const bodyParser = require('body-parser')

var multer  = require('multer') //[处理上传过来的文件]

// 创建目录
function createDir(dirPath) {
  try {
    fs.accessSync(dirPath)
  } catch(e) {
    fs.mkdirSync(dirPath)
  }
}

//要存储的目录
const uploadDir = __dirname + '/uploads'
createDir(uploadDir)
//存储文件配置
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir)
  },
  filename: function (req, file, cb) {
    //拼接成带时间戳的文件名(防止重名导致覆盖)
    var filename = file.originalname.replace(/\.([a-zA-Z]*)$/, `-${Date.now()}.`)
    cb(null, filename + RegExp.$1 )
  }
})
var upload = multer({ storage: storage })


var app = express();

/**[对index.html做映射] */
app.get('/', function(req, res) {
  fs.createReadStream(__dirname + './index.html', 'utf8').pipe(res)
})

// upload.single('logo') 中的这个字段一定要和上传上来的字段匹配
app.post('/upload', upload.single('logo'), function(req, res, next) {
  console.log( req.file.originalname )
  res.send('上传成功')
})

app.listen(3000)

console.log( 'server listening to 3000, http://localhost:3000' )

6、使用ejs模板引擎

使用ejs作为模板引擎,渲染变量、列表、包含子模块。

./server.js

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

/**[设置模板引擎的根目录]  */
app.set('views', './views')
/**[使用ejs模板引擎] */
app.set('view engine', 'ejs')

/**[对index.ejs做映射] */
app.get('/', function(req, res) {
  const data = {
    age: 12,
    name: 'david',
    list: [
      {  
        title: '水果',
        price: 19
      },
      {  
        title: '水果',
        price: 19
      },
      {  
        title: '水果',
        price: 19
      }
    ]
  }
  res.render('index.ejs', { data })
})

app.get('/about', function(req, res) {
  res.render('about')
})

app.listen(3000)

console.log( 'server listening to 3000, http://localhost:3000' )

./views/index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>使用ejs模板引擎</title>
</head>
<body>
  <%- include('header'); %>
  <h1>hello world</h1>
  <!-- 使用变量 -->
  <h2>姓名:<%= data.name %></h2>
  <h2>年龄:<%= data.age %></h2>
  <h3>购物车:<%= data.age %></h3>
  <ul>
    <!-- 使用循环 -->
    <% data.list.forEach(function (item) { %>
      <li>水果名:<span><%= item.title %></span>,价格:<span><%= item.price %></span></li>
    <% }) %>
  </ul>
</body>
</html>

./views/header.ejs

<nav>
  <ul>
    <li><a href="/">首页</a></li>
    <li><a href="/about">关于我们</a></li>
  </ul>
</nav>

./views/about.ejs

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
    <!-- 加入包含 -->
    <%- include('header') %>
  <h1>about.ejs</h1>
</body>
</html>

7、中间件

处理request、response插件称为中间件

./server.js

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

//中间件
app.use(function(req, res, next) {
  console.log(111)
  next()
})

//中间件
app.use(function(req, res, next) {
  next()
})

app.get('/', function(req, res, next) {
  res.send('<h1>hello</h1>')
})

app.listen(3000)

console.log( 'server listening to 3000, http://localhost:3000' )

输出:111 222

8、使用路由中间件

./server.js

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

const index = require('./routes/index')
const users = require('./routes/users')

app.use('/', index)
app.use('/users', users)

app.listen(3000)

console.log( 'server listening to 3000, http://localhost:3000' )

新建文件夹./routes./routes/index.js

var express = require('express')
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send('home')
})

module.exports = router

./routes/users.js

var express = require('express')
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send('users')
})

module.exports = router

这样配置,既可以完成将路由当做中间件。

9、项目实践

需求

添加事项、删除事项、展示事项列表;

备注

线上MongoDB网址:mLab

使用Mongolass操纵Mongoose数据库

posted @ 2019-05-31 17:27  DaivdAndLemon  阅读(194)  评论(0编辑  收藏  举报