简体   繁体   中英

Node js- req.body empty or undefined when handling ajax post request

this question asked by many users I saw all the solution and try to implement them but it is not working for me. I am trying to get data in node js function which is sent by ajax. my code in app.js

var express    = require('express')
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json())

var app = express()

app.post('/'uploadFileProduction',jsonParser,function(req,res){
     console.log("Hooorrey!!!!")
     console.log(req.body)

})

my ajax code part is

<script>
    $(function() {
        $('#submit_modal').click(function(e) {
           console.log('desired event fire!!!!!!!')
         e.preventDefault();
        var data = {};
                data.title = "title";
                data.message = "message";

           $.ajax({
               type: "POST",
               url: 'uploadFileProduction',
               data: JSON.stringify(data),

         });
     });
    });
</script>

when I am hitting this ajax function, I am getting null in body. I tried following solution but no luck

req.body empty on posts

Express.js POST req.body empty

Node.js req.body empty

https://github.com/expressjs/body-parser/issues/101

When I am printing req in node js, it is printing all data but in body it is {} only.

Please help.

I think the problem is because you send the body as a JSON object, but doesn't specify the contentType. The server doesn't know how to parse your body without knowing the correct content type. You should add it to make things work:

$.ajax({
   type: "POST",
   url: 'uploadFileProduction',
   data: JSON.stringify(data),
   contentType: "application/json; charset=utf-8" // <- this is what you should add
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM