【问题标题】:Undefined while console.log()未定义,而 console.log()
【发布时间】:2020-04-22 15:37:59
【问题描述】:

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>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') -%>

输出:Output is undefine

【问题讨论】:

  • console.log(req.body) 可能会帮助您解决问题
  • req.body 的内容是什么?你确定已经解析了正文吗(在content-type: application/x-www-form-urlencodedapp.use(bodyParser.urlencoded({extended: yourchoice}))时解析正文的形式@
  • 是的,我已经这样做了......但它仍然无法解析内容
  • 您是否在请求处理程序之前运行了适当的中间件来解析主体以填充req.body?如果没有,请参阅此答案No request info in POST from html form
  • 两个输入类都有引号未闭合

标签: javascript node.js express ejs body-parser


【解决方案1】:
 <button class="btn btn-primary" type="submit" name="submit">Publish</button>

不如这样,请尝试使用下面的代码

<input type="submit" class="btn btn-primary" name="submit"/>

【讨论】:

    【解决方案2】:

    req 中的空体总是因为缺少bodyparser

    请在应用声明后添加app.use(express.urlencoded()); 以启用对您的正文的解析。

    PS:您不能提供 HTML 按钮类型的提交。您可以使用输入类型提交或表单末尾的简单按钮来触发提交。

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 2018-06-29
      • 2018-12-21
      • 1970-01-01
      相关资源
      最近更新 更多