avatar

Catalog
Express使用笔记

安装

  • 初始化项目

    shell
    1
    npm init -y
  • 安装express

    shell
    1
    npm i --save express

hello-world

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var express = require('express')

var app = express()

// app.use('/public/', express.static('./public/'))

// 当省略第一个参数时,则使用省略/public/的方式来访问

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

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

基本路由

  • get

    Javascript
    1
    2
    3
    app.get('/', function(req, res) {
    res.send('hello express')
    })
  • post

    Javascript
    1
    2
    3
    app.post('/', function(req, res) {
    res.send('hello express')
    })

静态服务

Javascript
1
2
3
app.use('/public/', express.static('./public/'))

// 当省略第一个参数时,则使用省略/public/的方式来访问

配置art-template

  • 安装

    shell
    1
    npm install --save art-template express-art-template
  • 配置

    Javascript
    1
    2
    3
    // 配置使用 art-template模板引擎
    // 第一个参数表示,当渲染以 .html 结尾的文件的时候,使用模板引擎,第二个参数为适配。
    app.engine('html', require('express-art-template'))
  • 使用

    Javascript
    1
    res.render('index.html')

获取表单数据

在 express中没有内置获取表单post请求体的api,这里需要使用一个第三方包:body-parser

  • 安装

    shell
    1
    npm install --save body-parser
  • 配置

    Javascript
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    var express = require('express')
    // 引包
    var bodyParser = require('body-parser')

    var app = express()
    // 配置 body-parser
    // 只要加入这个配置,则可以在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))
    })

路由模块——router.js

  • router.js文件中

    Javascript
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    var express = require('express')

    // 创建一个路由容器
    var router = express.Router()

    // 把路由都挂在到router容器中
    router.get('/students', function (req,res) {

    })

    router.get('/students/news', function (req,res) {

    })

    // 把router导出
    module.exports = router
  • 在入口文件中

    Javascript
    1
    2
    3
    4
    var router = require('./router')

    // 把路由器挂在到app服务中
    app.use(router)
Author: 一只酱
Link: http://yoursite.com/2020/01/28/express/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
    微信
  • 支付寶
    支付寶