[英]Processing posted data in Express + Node.js?
我試圖捕獲Express和Node.js中從表單發送的信息。 以下是我的app.js和index.hjs的相關內容:
app.js
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
})
index.hjs
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>{{ title }}</h1>
<p>Welcome to {{ title }}</p>
<form method="post" action="/">
<input type="test" name="field1">
<input type="test" name="field2">
<input type="submit">
</form>
</body>
</html>
嘗試在http://expressserver.domain:3000上提交表單時,出現404錯誤。 有誰對這個問題有任何想法,並指出正確的方向嗎?
代替使用app.use
,使用真實的POST路由。
app.post("/", function(req, res) {
console.log(req.body);
res.json(req.body);
});
您需要一個實際的路由來啟動它,並且需要.post
而不是.use
,因為后者用於所有可能的HTTP動詞,這意味着它將嘗試訪問req.body
來獲取從未有過的內容(GET ,OPTIONS,HEAD等)並使腳本崩潰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.