提供了方便简洁的路由定义方式
对获取HTTP请求参数进行了简化处理
对模板引擎支持程度高,方便渲染动态HTML页面
提供了中间件机制有效控制HTTP请求
拥有大量第三方中间件对功能进行扩展
const express = require('express');
const app = express();
app.get('/',(request,response)=>{
response.end('hello express');
})
app.listen(80,()=>{
console.log('启动成功');
})
路由
const express = require('express');
const add = express();
const fs = require('fs');
add.get('/login',(request,response)=>{
console.log(request.get('host'));
const body = fs.readFileSync('./index.html')
response.end(body);
});
add.get('/register',(request,response)=>{
response.send('注册页面')
});
add.post('/login',(request,response)=>{
response.end('dengluchuli');
})
add.all('/text',(request,response)=>{
response.send('测试');
})
add.listen(80);
中间件
const express = require('express');
const add = express();
const moment = require('moment');
const fs = require('fs');
let record = function(request,response,next){
let path = request.url;
let date = moment().format('YYYY-MM-DD HH:mm:ss');
let str = `${date} ${path}\r\n`;
fs.writeFileSync('assgin.log',str,{flag:'a'})
next();
}
add.use(record);
add.get('/login',(request,response)=>{
response.send('注册页面');
})
add.get('/re',(require,response)=>{
response.send('处理页面');
})
add.listen(800)
const express = require('express');
const add = express();
let ruyou = function(request,response,next){
let admin = request.query.admin;
if(admin === '1'){
next();
}else(
response.redirect('/login')
)
}
add.get('/login',ruyou,(request,response)=>{
response.send('登录页面');
})
add.get('/register',ruyou,(request,response)=>{
response.send('注册页面');
})
add.listen(900)
获取请求体参数的中间件
const express = require('express');
const add = express();
var bodyParser = require('body-parser');
add.use(bodyParser.urlencoded({ extended: false }))
add.get('/index',(request,response)=>{
response.sendFile(__dirname+'/index.html')
})
add.post('/text',(request,response)=>{
console.log(request.body);
console.log(request.body.username);
})
add.listen(802);
|