上手一个node服务项目,搭建完服务器,最烦最烦的事-静态私服,脸上笑嘻嘻,心里乐( m )呵( m )呵( p ),这么多配置项要处理,不得烦死???于是你默默许愿:如果node有一个能一键配置所有需要读取的文件的技术该有多好,你心里刚想完,express就闪亮登场
Express
啥是express?从官网来看,express 是一个保持最小规模的灵活的 Node.js Web 应用程序开发框架,为 Web 和移动应用程序提供一组强大的功能。看出来了,说白了就是极简还强的一批优化版node呗,接下来我们看看有哪些常见的优化
express下载
npm install express -g//win用户
$ npm install express -g//mac用户
cnpm install express -g//淘宝镜像
服务器搭建
let express = require("express");
const app = express();
app.get("/",(req,res)=>{
res.send("hello world!")
})
app.listen(8888)
参数体
get请求
参数体放在query中
req.get("/",(req,res)=>{
let uname = req.query.uname;//获取ajax中GET方式传的uname
})
post请求
参数体放在body中,要取得参数需要借助一个中间插件json解析中间件(body-parser)
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));
app.post("/test",(req,res)=>{
let uname = req.body.uname//获取ajax中POST方式传的uname
})
静态伺服
当我们需要配置project页面下面的静态文件,一键static就可以了,不需要一个个配置,真的是十分的方便,万分的简单
app.use(express.static("./project"))
路由匹配
app.get("/test",(req,res)=>{//匹配接口为/test的
res.send("hello world!")
})
app.get("/a*c",(req,res)=>{//匹配接口为/a(任意字符)c的:/abc /acc /adc
res.send("hello world!")
})
app.get(/^\/[1-9a-zA-Z]$/,(req,res)=>{//匹配接口为/任意数字字母: /1aA
res.send("hello world!")
})
Cookie
let cookieParser = require('cookie-parser');
app.use(cookieParser())//使用中间件
app.get("/setcookie",(req,res)=>{//设置cookie
res.cookie('cookie名字','cookie值',{maxAge:10000})
res.send("设置成功!")
})
app.get("/getcookie",(req,res)=>{//获取cookie
res.send(req.cookies.username)
})
cookie设置的最后{}中的参数列表
参数 | 意义 |
---|---|
domian | 域名 |
expires | 过期时间(s),过了已设置的点cookie就失效 |
secure | 值为true时,http中失效,https中有效 |
httpOnly | 防止脚本获取cookie,防止xss攻击 |