Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request body is empty when making a POST request via HTML form

Tags:

node.js

I'm having a problem with symptoms similar to this question and several others, though the answers haven't helped me. I'm trying to submit a password via a simple HTML form to a Node app, but the request body keeps coming back empty.

Server:

app.use(bodyParser.urlencoded({extended: true}));

router.post('/login', (req, res) => {
  console.log(req.body);
  console.log(req.headers['content-type']);
});

Form:

<form action="/login" method="post">
  <input type="password" id="password">
  <button type="submit">Log In</button>
</form>

If I submit the form, I get the following:

{} // req.body
'application/x-www-form-urlencoded' // req.headers['content-type']

However, if I try to curl the endpoint, I get a non-empty req.body:

$ curl -X POST localhost:5000/login -d 'password=testpw'

// Output
{ password: 'testpw' }
'application/x-www-form-urlencoded'

What am I doing wrong?

like image 845
ericgio Avatar asked Jan 08 '17 09:01

ericgio


1 Answers

Problem is in your form

<form action="/login" method="post">
  <input type="password" id="password">
  <button type="submit">Log In</button>
</form>

Your input doesn't have a name element

Should be

<input name="password" type="password" id="password">
like image 186
Alex Avatar answered Oct 17 '22 09:10

Alex