原生的http在某些方面表现不足以应对咱们的开发需求,使用框架能够加快咱们的开发效率html
mkdir express
cd express
npm init -y
npm install express --save
复制代码
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 ...')
})
复制代码
app.get('/', function (req, res) {
res.send('hello world')
})
app.post('/',function (req, res){
res.send('hello world')
}
复制代码
输入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/'))
复制代码
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'
})
}
复制代码
安装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))
})
复制代码