繁体   English   中英

Express.js解析表单主体

[英]Express.js parsing form body

有以下形式:

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <% include menu %>
    <h1><%= title %></h1>
    <p>Fill in the form below to add a new post.</p>
    <% include messages %>
    <form action='/post' method='post'>
      <p>
        <input type='text' name='entry[title]' placeholder='Title' />
      </p>
      <p>
        <textarea name='entry[body]' placeholder='Body'></textarea>
      </p> 
      <p>
        <input type='submit' value='Post' />
      </p>
    </form>
  </body>
</html>

Express.js代码部分:

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(session({secret: 'SomeSecretKey'}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

但是,当我发布此表单时,我得到以下json响应(通过res.json({body: req.body})

{"body":{"entry[title]":"111","entry[body]":"222"}}

而且我不能使用req.body.entry.title(错误:无法获得未定义的标题)。 我该如何解决? 谢谢!

设置extendedtrue ,将使用qs模块解析支持嵌套的主体。

app.use(bodyParser.urlencoded({ extended: true }));

我不确定Node in Action的最新版本是什么,但是我发现很多练习已经过时,只是要牢记。

如果您想快速修复,请删除entry []。 因此,将名称命名为标题和正文,然后您将获得...

{"body":{title:"111",body:"222"}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM