Web  Hopeful
Web Hopeful

Reputation: 761

Processing posted data in Express + Node.js?

I am attempting to capture the information that is being sent from a form in Express and Node.js. Here are the relevant contents of my app.js and 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>

When attempting to submit the form on http://expressserver.domain:3000, I receive a 404 error. Does anyone have any ideas on what the issue is and point me in the right direction?

Upvotes: 0

Views: 395

Answers (2)

Instead of using app.use, have a real POST route.

app.post("/", function(req, res) {
  console.log(req.body);
  res.json(req.body);
});

You need an actual route for it to kick in, and you want .post, not .use, because the latter is for all possible HTTP verbs, which means it'll try to access req.body for things that never have one (GET, OPTIONS, HEAD, etc) and crash your script.

Upvotes: 6

Related Questions