500 TypeError: Cannot read property 'connect.sid' of undefined

1:在写passport验证测试用例时,发现有几个引用中间件顺序的错误,检查发现,passport验证写的是session,在传错误信息的时候req.flash调用也需要用到session中间件,否则会报错:

我先引用  app.use express.session({secret: 'keyboard'})

2:引用后,运行代码,又报错:

由于会话是使用cookie实现的,因此还得引用cookie中间件
app.use express.cookieParser()

cookie一定要写到session中间件的前面,原因:

Middleware order matter in Express, as they are executed in the order you defined them. In your case, the cookieParser middleware adds some information that is used by the session middleware.

You can check connect's documentation:

Session data is not saved in the cookie itself, however cookies are used, so we must use the cookieParser() middleware before session().

3:  发现了个很妖的情况,在form窗里里submit后,input输入框的数据居然没有带到body里,每次body都是空的,检查出来发现urlencoded中间件居然被我屏蔽掉了,好火大,

app.use express.json()
app.use express.urlencoded()

其实 bodyParser() 支持 JSON, urlencoded和multipart requests的请求体解析中间件。 这个中间件是json(), urlencoded(),和multipart() 这几个中间件的简单封装

app.use(express.bodyParser());   // 等同于:
                      app.use(express.json());
                      app.use(express.urlencoded());
                      app.use(express.multipart());
那为什么不用express.bodyParser来的方便????????当我使用bodyParser()替换时,运行警告:
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0
原来connect移除了所有中间件,connect.multipart()更是访问不到了,express版本:  "version": "3.5.1", 难怪用express自动建项目的时候直接使用的app.use express.json();app.use express.urlencoded()

其他人的解释:connect 发布了 3.0, 移除了所有中间件。express 发布了 4.0,移除了 connect 的依赖。express 老版本引用了 connect 2.x,所以会有这个提示。
express.multipart()中间件用于文件上传,如果没有文件上传建议就别用了

在做一个文件上传的时候,需要用到req.files这个属性,如果不用app.use(express.bodyParser())这个代码就会报错了,这个时候是不是只能回到express的旧版本呢????

原文地址:https://www.cnblogs.com/Joans/p/3954046.html