NodeJs获取不到POST参数

时间:2021-11-26 20:59:37

NodeJs报错,从网页端获取不到POST参数,提示错误类似如下

TypeError: Cannot read property 'username' of undefined
    at C:\Users\RENYUZHUO\Desktop\_\Code\Server_NodeJs\login.js:13:29
    at Layer.handle [as handle_request] (C:\Users\RENYUZHUO\Desktop\_\Code\Server_NodeJs\node_modules\express\lib\router\layer.js:82:5)
    at next (C:\Users\RENYUZHUO\Desktop\_\Code\Server_NodeJs\node_modules\express\lib\router\route.js:100:13)
    at Route.dispatch (C:\Users\RENYUZHUO\Desktop\_\Code\Server_NodeJs\node_modules\express\lib\router\route.js:81:3)
    at Layer.handle [as handle_request] (C:\Users\RENYUZHUO\Desktop\_\Code\Server_NodeJs\node_modules\express\lib\router\layer.js:82:5)
    at C:\Users\RENYUZHUO\Desktop\_\Code\Server_NodeJs\node_modules\express\lib\router\index.js:233:24
    at Function.proto.process_params (C:\Users\RENYUZHUO\Desktop\_\Code\Server_NodeJs\node_modules\express\lib\router\index.js:311:12)
    at C:\Users\RENYUZHUO\Desktop\_\Code\Server_NodeJs\node_modules\express\lib\router\index.js:227:12
    at Function.match_layer (C:\Users\RENYUZHUO\Desktop\_\Code\Server_NodeJs\node_modules\express\lib\router\index.js:294:3)
    at next (C:\Users\RENYUZHUO\Desktop\_\Code\Server_NodeJs\node_modules\express\lib\router\index.js:188:10)

原因其实是因为没有:

app.use(bodyParser.urlencoded({extended: false}))

那这句话到底是干嘛用的呢?

就是将网页端发送的请求的实体通过中间件解析出来,以便使用。

参见:https://github.com/expressjs/body-parser