我正在 try catch 从 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 等),并使您的脚本崩溃。
关于javascript - 在 Express + Node.js 中处理发布的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27138112/