Tuesday 6 June 2017

body-parser(node.js) not able to understand form POST using fetch browser api

on sending form data using fetch api from browser to nodejs server, body-parser at node.js server not showing data sent but some object that is not understandable.

Here is the html form code:

<body>
<form action="#" id="formToSubmit">
    <input type="text" name="name" value="xyz">
    <input type="text" name="phone" value="7777777777">
    <input type="submit" value="submit" onClick="submitForm()">
</form>

<script>
    function submitForm(){
        var form = new FormData("formToSubmit");
        fetch("http://localhost:8080/ppum", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'                 
            },
            body: form
        })
        .then(res => res.json())
        .then(data => console.log(data));

    }
</script>

Here is the node server code for body parser:

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

Here is the output of "req.body" at server:

{"------WebKitFormBoundarydcytJaR8vD9SW2vF--\r\n":""}

What is the problem here, why is the output like as shown and how to correct it.



via devprashant

No comments:

Post a Comment