express(Node.js)

原生的http在某些方面表现不足以应对咱们的开发需求,使用框架能够加快咱们的开发效率html

1. 安装

mkdir express
     cd express
     npm init -y
     npm install express --save
复制代码

2. hello word

var express = require('express')
    var app = express()
    app.get('/', function (req, res) {
      res.send('hello world')
    })
    app.listen(3000, function () {
      console.log('express app is running ...')
    })
复制代码

3. 基本路由(请求方法+请求路径+请求处理函数)

app.get('/', function (req, res) {
  res.send('hello world')
})
app.post('/',function (req, res){
 res.send('hello world')
}
复制代码

4. 静态服务(统一处理静态资源)

输入url地址:/public/xxx
app.use('/public/', express.static('./public/'))
输入url地址:/a/xxx
app.use('/a/', express.static('./public/'))
输入url地址:xxx
app.use(express.static('./public/'))
复制代码

5. 在express配置中使用模板art-template

  • 安装
npm install --save art-template
    npm install --save express-art-template
    //express-art-template依赖了art-template,因此要一块儿下载
复制代码
  • 配置
app.engine('html', require('express-art-template')
复制代码
  • 使用
app.get('/', function (req, res) {
    //express 默认去项目的viwe目录下找index.html
      req.render('index.html', { 
        title:'hello word' 
      })
    }
复制代码

6. 在express中获取表单Get请求参数

  • express内置了一个api,能够经过req.query获取

7. 在express中获取表单post请求体数据

  • 安装express

    npm install body-parser --savenpm

  • 配置json

var express = require('express')
    var bodyParser = require('body-parser')
    var app = express()
    
    //配置 body-parser 中间件(插件,专门用来解析表单 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')
     //req请求对象中就会多一个body属性,也就是经过req.body表单post请求体数据
      res.end(JSON.stringify(req.body, null, 2))
    })
复制代码
相关文章
相关标签/搜索
本站公众号
   欢迎关注本站公众号,获取更多信息