express借助中间件可以更加高效的完成工作
Express-static:
Express-static 是express一个读取静态文件的中间件,安装:npm install express-static
使用方法为server.use(static(rootpath))这样用户访问的文件可以转到rootpath的目录下了
比如输入localhost:8080/index.html; 实际上访问的是rootpath下的index.html
const express = require('express');
const static = require("express-static");
var server = express();
server.listen(8080);
server.use(static('./www'));
//比如放了一张1.jpg的图片在www文件夹下,浏览器输入localhost:8080/1.jpg就可以访问到了
Body-parser:
bodyparser是用来解析post请求url中的请求体部分的,使用方法为server.use(bodyparser.urlencoded({extended:false}));
extended参数为是否开启扩展模式。
const express = require('express');
const bodyparser = require("body-parser");
var server = express();
server.listen(8080);
server.use(bodyparser.urlencoded({extended:fasle}));
server.use("/", function(req, res){
//可以获取post数据的query部分
console.log(req.body);
res.end();
});