node.js - req.body.username 未定义

标签 node.js express body-parser

在express js中,我使用主体解析器来获取用户名。当我尝试获取用户名时,它返回未定义。谁能帮我吗?

app.use(session({
 cookieName: 'session',
 secret: "Shh_It's_a_secret",
 duration: 100000 * 100000
}));
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/home', (req, res) => {
if(req.body.username){
 res.send('Invalid Username, Press The Back Button To Try Again');
} else if (!req.body.username) {
  app.use(express.static(__dirname + '/NerdFestProjectHomepage.html'));
  res.sendfile('NerdFestProjectHomepage.html');
  console.log(req.body.username);
}
})

当我尝试获取 req.body.username 时,它​​返回未定义。

最佳答案

这是一个 GET 请求。 在 Express 中,无法使用 GET 请求发送“正文”。

将 GET 请求更改为 POST 请求:

app.post('/home', cb );

并在 View 中使用:

<form action="/home" method="POST"></form>

关于node.js - req.body.username 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54526862/

相关文章:

node.js - (libuv)kqueue(): Too many open files in system when trying to write a file in Node Js

javascript - Node 从url中获取json

json - Node.js body-parser 不会解析 json 中带有方括号的输入名称

node.js - 在生产实例上找不到socket.io.js

javascript - 如何使用带有导入的 Body Parser 而不是必需的? ES6

jquery - NodeJS中从AJAX请求获取数据并存储在DB中

mysql - 如何一次启动多个 Node 脚本,或将每个脚本与 main 连接以一起启动

node.js - 嵌套多个异步等待

javascript - 从 3.x 迁移后 Express.js 4.x session 未定义

javascript - babel 与express js :avoid relative path imports