Express入門

一、請求與響應

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能夠查看:www.expressjs.com.cn/4x/api.html…javascript

**nodemon:**一個能夠監聽文件修改,自動重啓node服務的插件。html

只須要全局安裝,使用nodemon server命令,會自動查找當前目錄的server.jsjava

二、路由參數(動態路由)

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' )
複製代碼

路由可使用正則表達式node

三、查詢字符串

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' )
複製代碼

四、解析POST參數

解析post請求參數須要藉助body-parse中間件,安裝這個中間件。ajax

解析Form Data數據正則表達式

這種方式的請求Content-Type: 'application/x-www-form-urlencoded'數據庫

這種是form表單提交過來的數據,用法./server.jsexpress

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數據json

這種請求方式的Content-Type: 'application/json;charset=UTF-8'api

使用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' )
複製代碼

五、上傳文件

安裝處理文件程序: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' )
複製代碼

六、使用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>
複製代碼

七、中間件

處理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

八、使用路由中間件

./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
複製代碼

這樣配置,既能夠完成將路由當作中間件。

九、項目實踐

需求

添加事項、刪除事項、展現事項列表;

備註

線上MongoDB網址:mLab

使用Mongolass操縱Mongoose數據庫

相關文章
相關標籤/搜索