Javascript 未定义while console.log()
app.js中的代码Javascript 未定义while console.log(),javascript,node.js,express,ejs,body-parser,Javascript,Node.js,Express,Ejs,Body Parser,app.js中的代码 app.post('/compose', function(req, res){ const post = { title: req.body.postTitle, content: req.body.postBody }; console.log(post); res.redirect('/compose'); }); ejs文件中的代码 <%- include('partials/header') -%> <h1&
app.post('/compose', function(req, res){
const post = {
title: req.body.postTitle,
content: req.body.postBody
};
console.log(post);
res.redirect('/compose');
});
ejs文件中的代码
<%- include('partials/header') -%>
<h1>Compose</h1>
<form action="/compose" method="post">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control name="postTitle">
<label>Post</label>
<textarea class="form-control name="postBody" rows="8" cols="80"></textarea>
</div>
<button class="btn btn-primary" type="submit" name="submit">Publish</button
</form>
<%- include('partials/footer') -%>
组成
标题
发布<代码>发布
请尝试使用以下代码,而不是此代码
<input type="submit" class="btn btn-primary" name="submit"/>
由于缺少
bodyparser
,所以req中的一个空主体始终是空的
请添加app.use(express.urlencoded())代码>应用程序声明后,以启用对身体的解析
PS:您不能给HTML按钮类型“提交”。您可以使用输入类型submit或表单末尾的简单按钮来触发提交。console.log(req.body)
可能会帮助您解决问题req.body
的内容是什么?您确定已经解析了正文(在内容类型:application/x-www-form-urlencoded
即app.use(bodyParser.urlencoded({extended:yourchoice})时解析正文的表单中)
是的,我已经这样做了……但是它仍然没有解析内容。您是否在请求处理程序之前运行了适当的中间件来解析正文以填充req.body
?如果没有,请参阅此答案。两个输入类都有未关闭的引号
<input type="submit" class="btn btn-primary" name="submit"/>