[英]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(錯誤:無法獲得未定義的標題)。 我該如何解決? 謝謝!
設置extended
為true
,將使用qs
模塊解析支持嵌套的主體。
app.use(bodyParser.urlencoded({ extended: true }));
我不確定Node in Action的最新版本是什么,但是我發現很多練習已經過時,只是要牢記。
如果您想快速修復,請刪除entry []。 因此,將名稱命名為標題和正文,然后您將獲得...
{"body":{title:"111",body:"222"}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.