Reputation: 39
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?
Upvotes: 2
Views: 1752
Reputation: 106698
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.
Upvotes: 3
Reputation: 281
In action attribute you don't need to specific the host just specify path such as "/add".
Upvotes: 0