在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/