node express 应用笔记关键点

1、处理客户端 POST数据(标签 <form>), req.body 对象

app.js

var bodyParser = require('body-parser');
... ...
... ...
app.use(bodyParser.json());          // 处理post 请求 
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded  
 
路由post回调函数
router.post('/', (req, res) => {
  console.log('收到用户登录POST数据:' + JSON.stringify(req.body, null, ' '));
  // res.json(req.body);// 直接发送 对象
  res.send(JSON.stringify(req.body, null, ' '));// 转好 string 再发送
});
 
2、修改静态资源默认首页 login.html(任意)
app.use(express.static(__dirname+"/public",{index:"login.html"}));
 
3、express-session 读写 session 和 cookie
  app.js 初始化处
//本网站应用开启session 中间件,使用方法 session({})
app.use(session({
  secret: 'secret',         // 对session id 相关的cookie 进行签名,随便放置
  resave: false,
  saveUninitialized: false, // 是否保存未初始化的会话
  cookie: {
    maxAge: 1000 * 60 * 3,  // 设置 session 的有效时间,单位毫秒
  }
}));
  get post 请求处
  req.session.userName = username; //使用属性,记录登录的用户名
  res.cookie('userName', username, { maxAge: 1000 * 60 * 3, singed: true }); //使用函数(),同时cookie 也标志 userName
   总结:服务器后台可以读写session 和 cookie,而前端js只能读取 cookie(可禁写)
  附加参考:https://www.jianshu.com/p/5a0ccd1ee27e
4、
 
原文地址:https://www.cnblogs.com/qinlongqiang/p/11679296.html