处理Express + Node.js中发布的数据?

Web*_*ful 0 javascript json node.js express

我试图捕获从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))
})
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

尝试在http://expressserver.domain:3000上提交表单时,收到404错误.有没有人对问题是什么有任何想法,并指出我正确的方向?

Mik*_*ans 6

而不是使用app.use,有一个真正的POST路线.

app.post("/", function(req, res) {
  console.log(req.body);
  res.json(req.body);
});
Run Code Online (Sandbox Code Playgroud)

你需要一个实际的路径才能启动它,你想要的.post不是.use,因为后者适用于所有可能的HTTP动词,这意味着它会尝试访问req.body从未有过的东西(GET,OPTIONS,HEAD等)并崩溃你的脚本.