-1

I'm trying to access the data in a POST request however when I console.log(req.body) I'm just getting an empty {}.

I feel like my error is somewhere in the markup?

Here is the relevant client side markup

<div id='create' class="card">
  <form method = 'post' action='/'>
    <textarea placeholder="Enter your name"></textarea><br>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
</div>

relevant backend code

app.use(bodyParser.json());

app.post('/',(req, res)=>{
    console.log(req.body);

});

If the user enters "John" in the textarea I'd like the page to refresh and the name John to appear in the terminal.

I plan to export that data to another file that is connected to my mongodb

Heyrio
  • 129
  • 2
  • 11

3 Answers3

0

You're telling bodyParser to parse the body as if it's JSON. However, a standard <form> will submit data not as JSON, but as application/x-www-form-urlencoded.

To read that in your express app, you'll instead need something like this:

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

Allowing both JSON and form data

If you want to allow both URL encoded and JSON data, you can combine both methods:

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

A full example can be found here.


Built-in alternative

Good to note: if you're using a recent version of Express, you can also exchange the body-parser module for a built in alternative:

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

This still uses body-parser underneath (and therefore has the exact same synax), but might look slightly neater in your app.

tschoffelen
  • 518
  • 7
  • 21
  • body-parser deprecated undefined extended: provide extended option app.js:9:20 I've added that and when I do and run it I get this in the terminal. I'd also like to add that on client page when I hit the submit but the page will continually load and say waiting for localhost. – Heyrio Apr 16 '19 at 18:55
-1

This problem has been solved by a combination of two things.

1.) I needed to add app.use(bodyParser.urlencoded()) because it was not sent by the form as if it were JSON data.

2.) I needed to add a name to the textarea.

Heyrio
  • 129
  • 2
  • 11
-1

When looking at your console log statement you are dumping the resource which was an empty object. Given that information, I looked at your HTML.

When dealing with forms in HTML, you will have a form tag, but the inputs, textarea etc inside of the form will need a name attribute in order to build the payload correctly.

<textarea name="test"></textarea>

will simply show a new property in the request payload called test which contains the contents for what is in the textarea at the time the form was submitted.

Fallenreaper
  • 10,222
  • 12
  • 66
  • 129