2

I was tring to create an API POST using Node.js and express. I was just trying to post some data using html form:

<form id="myform" action="http://localhost:4000/add" method="post" enctype="application/json">
    <input type="text" name="name" id="name" />
    <input type="submit" id="submit" />
</form>

The server would just receive the POST request and display the body into console.log.

router.post('/add', function (req, res){
    console.log("request: "+JSON.stringify(req.body));
})

What is being received at the console is: request: {}

Trying to post into the same api using Postman - raw, JSON(application/JSON), things work fine.

Can someone please tell me what is wrong with what I am doing?

2 Answers2

3

Browsers do not support submitting HTML forms as application/json. Most browsers would probably ignore the value and send the form as the default enctype which is application/x-www-form-urlencoded. To parse that, you'd need to use an appropriate middleware. One such example is the body-parser module's urlencoded() middleware.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Great! Thanks, solved my problem: I just added `app.use(bodyParser.urlencoded({ extended: false }))` additional to the json body-parser i already had. – Zaphoid Jun 17 '17 at 18:44
0

In action attribute you don't need to specific the host just specify path such as "/add".

mn.agg
  • 281
  • 1
  • 8