原生的http在某些方面表现不足以应对我们的开发需求,使用框架可以加快我们的开发效率
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请求体数据
-
安装
npm install body-parser --save
-
配置
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))
})