Ajax post data from form to send to express js body parser

11,499

The body-parser library does not handle data encoded with multipart/form-data. If you want to send that type of data, you should be using something like the multer middleware.

But in your case, I think you can get away without having to use the FormData interface. You can just rewrite your browser code as such:

const $form = $('#addUserForm')

$form.on('submit', submitHandler)

function submitHandler (e) {
  e.preventDefault()

  $.ajax({
    url: '/addUserFormSubmit',
    type:'POST',
    data: $form.serialize()
  }).done(response => {
    console.log(response)
  })
}
Share:
11,499
Sujay U N
Author by

Sujay U N

If ( YouDoNotKnwMe ) { String Name = “Sujay U N” String Mobile = 9964120147 String EMail = "[email protected]" If ( YouLykToKnwMorAbtMe ) { String VisitWebsite = www.sujayun.cf String FacebookPage = https://www.facebook.com/dijisuji String TwitterPage = https://twitter.com/sujayun String LinkedinPage = https://in.linkedin.com/in/sujayun String StackoverflowPage = https://stackoverflow.com/users/5078763/sujay-u-n String GitlabPage = https://gitlab.com/dijisuji String GithubPage = https://github.com/sujayun } }

Updated on June 04, 2022

Comments

  • Sujay U N
    Sujay U N almost 2 years

    I am tring to send Form data to node js via ajax,
    I am using express with body parser on node js
    But I am getting undefined in req.body

    I searched every in net and tried many things and nothing worked for me Kindly help me with the correct way of doing this.

    |*| Html Code :

    <html lang="en">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <title>Add</title>
    </head>
    <body>
    
        <h1>Welcome to Website </h1>
        <form id="addUserForm">
            <h3> Enter the your details : </h3>
            Name :<br><input type="text" name="nameView"><br><br>
            Email :<br><input type="email" name="mailView"><br><br>
            Mobile :<br><input type="number" name="mobileView"><br><br>
            <input type="submit" value="Submit">
        </form>
    

    |*| Ajax Code :

        <script>
            $(document).ready( function()
            {
                $('#addUserForm').submit(function()
                {
                    var formDataVar = new FormData($(this)[0]);
    
                    console.log(formDataVar);
                    $.ajax({
                        url: '/addUserFormSubmit',
                        type:'POST',
                        data: formDataVar,
                        dataType: 'json',
                        contentType: false,
                        processData: false,
                    }).done(function(ResJryVar)
                    {
                        console.log(ResJryVar);
                    });
                })
            });
    
        </script>
    </body>
    
    </html>
    

    |*| I also tried :

    var formDataVar = new FormData();
    formDataVar.append( 'nameView', input.files[0] );
    formDataVar.append( 'mailView', input.files[1] );
    formDataVar.append( 'mobileView', input.files[2] );
    

    and

    var formDataVar = {};
    $.each($('#addUserForm').serializeArray(), function(i, field)
    {
        formDataVar[field.name] = field.value;
    });
    

    |*| Node Js Code :

    var express = require("express");
    var bodyParser = require("body-parser");
    var app = express();
    
    app.listen(8888,function()
    {
        console.log("Server Started and Running ...");
    });
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));
    
    app.get('/',addUserFormFnc);
    app.post('/addUserFormSubmit',addUserSubmitFnc);
    
    function addUserFormFnc(req, res)
    {
        res.sendFile('addUser.html', {root: __dirname });
    }
    
    function addUserSubmitFnc(req, res)
    {
        console.log("Data Received : ");
        var userObjVar =
        {
            nameView: req.body.nameView,
            mailView: req.body.mailView,
            mobileView: req.body.mobileView
        };
        console.log(userObjVar);
        res.send(userObjVar);
    
    }
    

    • djfdev
      djfdev over 6 years
      If you have url encoded data, it should be available on req.body, not req.data. For multipart/form-data, check out the multer middleware package.
    • Sujay U N
      Sujay U N over 6 years
      sorry edited my question. its req.body. I am just using form. action='/addUserFormSubmit' works. but when I send from ajax, it wont work
  • Sujay U N
    Sujay U N over 6 years
    Can you give an explain how to use multer for only fields. The documentation explains only about files.
  • djfdev
    djfdev over 6 years
  • djfdev
    djfdev over 6 years
    According to the multer docs, any text fields will be available as properties of req.body. But again, you shouldn't need to use this library unless you are sending files.
  • Soni Kumari
    Soni Kumari about 5 years