Reputation: 330
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
Express.js POST 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.
Upvotes: 3
Views: 5164
Reputation: 1586
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
});
Upvotes: 4