Andy
Andy

Reputation: 30428

How can I get the parameters when POSTing from a form using Express?

I'm having problems getting the POSTed data when using a form in Express.

My form is pretty straight forward:

<form action="/api/v1/items" method="post">
    <p>
        <span>Name:</span><br>
        <input type="text" id="name">
    </p>
    <p>
        <span>Priority:</span><br>
        <input type="text" id="priority">
    </p>
    <p>
        <span>Comment:</span><br>
        <input type="text" id="comment">
    </p>
    <input type="submit" value="Add Item">
</form>

Here is the implementation of the endpoint on the server:

const express = require('express');

const router = express.Router();

router.post('/', (req, res, next) => {
    const data = {
        'name': req.body.name,
        'priority': parseInt(req.body.priority),
        'comment': req.body.comment
    };

    // do something with the data
});

module.exports = router;

The route should be registered correctly:

var app = express();
var items = require('./routes/items');

app.use('/api/v1/items', items);

The problem is that when the form is submitted, req.body has no parameters.

I created my app using the Express generator, so the body-parser middleware should be set up correctly:

var bodyParser = require('body-parser');

...

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

The strange thing is that if I use curl to POST the data, the parameters are sent correctly:

curl --data "name=Something&priority=1&comment=Whatever" http://127.0.0.1:3000/api/v1/items

Since curl works, this tells me that something is wrong with my form, although I have no idea what could be wrong there.

What do I need to do in order to get the parameters POSTed from the form to be parsed correctly in Express?

Upvotes: 0

Views: 47

Answers (1)

Sergey Lapin
Sergey Lapin

Reputation: 2693

Inputs in your form should have names rather than ids

<form action="/api/v1/items" method="post">
    <p>
        <span>Name:</span><br>
        <input type="text" name="name">
    </p>
    <p>
        <span>Priority:</span><br>
        <input type="text" name="priority">
    </p>
    <p>
        <span>Comment:</span><br>
        <input type="text" name="comment">
    </p>
    <input type="submit" value="Add Item">
</form>

You may find specification on form submission useful.

Upvotes: 2

Related Questions