Ajax post request can't get data with express router - ajax

I'm using express.Router() to manage my routes.
then using Ajax post request send some data to it. but I can't get the data.
ajax code :
$.ajax({
url: '/custom',
type: 'POST',
contentType: 'application/json; charset-utf-8',
dataType: 'json',
processData: false,
data: JSON.stringify({ "key": "values" }),
success: function(data) {
console.log(data.toString());
}
})
express code:
var express = require('express');
var router = express.Router();
router.post('/custom', function(req, res) {
console.log(req.body);
console.log(req.params);
console.log(req.query);
res.write(JSON.stringify());
res.end();
});
but all the logs are empty.

The issue is because the content-type header in your ajax is malformed.
Instead of
contentType: 'application/json; charset-utf-8' it should be contentType: 'application/json; charset=utf-8'.
Assuming you are using the bodyParser.json() middleware, this would cause the body to not be parsed, which would print an empty body. When you sent the requests with Postman the proper headers were sent, which is why it worked there but not from the ajax request.

Related

Ajax request response code 419 even csrf token is available in request

I have a simple ajax request which is returning 419 even csrf token is available in both the ajax setup header and inform data as well here is my code.
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var formData = new FormData();
formData.append('_token', $("input[name='_token']").val());
formData.append('request_id', $('#request_id').val());
var request = $.ajax({
url: appUrl + "/admin/schedule-detailing-requests",
type: "POST",
data: formData,
processData: false,
contentType: false,
cache: false,
dataType: "json",
// headers: headers
});

ASP.NET Core FromBody is null on AJAX POST but populates in Postman

I'm trying to perform an AJAX post but I keep getting a null FromBody in my .NET controller. I think it has to do with how I'm formatting my AJAX post.
When I attempt to post with AJAX I get a null FromBody.
var data = {
Date: "2016-12-01",
BurnIdx: 23,
BurnStatIdx1: 3,
BurnStatIdx2: 3,
BurnStatIdx3: 3,
BurnSevIdx: 5,
WorkOrder: 32426,
Comment: "Hi"
};
$('#submit').on('click',function () {
$.ajax({
type: 'POST',
url: 'Home/BurnerMapUpdate',
dataType: 'json',
contentType: 'application/json',
data: data,
success: function (result) {
console.log('Data received');
console.log(result);
}
});
});
However, when I attempt a post in Postman it's successful.
Figured out my problem. Needed to use JSON.stringify on my data.
$('#submit').on('click',function () {
$.ajax({
type: 'POST',
url: 'Home/BurnerMapUpdate',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
console.log('Data received');
console.log(result);
}
});
Not only the JSON.stringify().
If your data don't match with csharp class data it doesn't receive anything.
Like if you define in the class a field with int type, and send it in the json like "1", it happens to receive the whole data as null
I know you are already figured out of this problem. But I faced with the same just right now. My mistake was I used BODY parameter instead DATA in ajax request.
My Invalid ajax:
function sendRequest(url, method, body, callbackOk, callbackFail) {
$.ajax({
url: url,
body: JSON.stringify(body),
method: method,
contentType: 'application/json; charset=utf-8',
success: callbackOk,
error: callbackFail
})
Valid:
function sendRequest(url, method, body, callbackOk, callbackFail) {
$.ajax({
url: url,
data: JSON.stringify(body),
method: method,
contentType: 'application/json; charset=utf-8',
success: callbackOk,
error: callbackFail
})
}

400 using Axios to make a post request to Django Rest Framework

I'm working with learning some javascript to make a post to a little rest API I created with django rest. I have a post that works when I was working with jQuery but now I am reimplementing using Vue.js and am hitting a snag. When I do the below post request I get a 400 error and am not sure what I am missing. I would imagine something with my header is incorrect? Any advice would be welcome.
axios({
method: 'post',
url: '/api/matches/',
data: JSON.stringify(data),
headers: {
"X-CSRFToken": csrfToken,
"Content-Type": "application/json"
}
})
jQuery post for reference:
$.ajax({
type: "POST",
url: "/api/matches/",
data: JSON.stringify(final_data),
success: function() {},
error: function(err) {console.log(err)},
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain:false,
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
});

Scraping an AJAX generated JSON feed

I'm trying to scrape a webpage which is generating pages via an AJAX call from a JSON response. This is the code on the page:
var data = JSON.stringify({
organizationId: organizationId,
concertId: concertId,
})
$.ajax({
type: "POST",
url: "/getdata",
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
});
}
So, I try to scrape this via a Request
data = '{"organizationId":"1","concertId":"8918"}'
url = 'http://www.domain.com/ajax/getdata'
request = Request( url = url ,
method='POST',
body=data,
headers={'Content-Type':'application/json'})
But this doesn't work; the parse function is not called. Am i missing something?

wcf service json 400 Bad Request

I get a 400 Bad Request error when I try to call WCF service from client side using ajax. Following is my code,
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json)]
string[] GetUser(string Id);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:58055/Service1.svc/GetUser",
crossDomain: true,
data: '{"Id": "3"}',
contentType: "application/json; charset=utf-8",
dataType: "json", //Expected data format from server
processdata: true, //True or False
success: function (msg) {//On Successfull service call
alert(msg.GetUserResult[0]);
console.log("success " + msg);
},
error: function (msg) {//On Successfull service call
console.log(msg);
}
});
Any insights would be really helpfull...
The first thing you should try is hit the URL using fiddler(so that you could post your data too) and see if you get the same error.
Are you making a cross domain request. From the example it looks like you are not. Could you remove
crossDomain: true,
line and try the jquery again.
There are other options also which unnecessay like processdata. Suggest you to use the following code and see if it works or not.
$.ajax({
type: "POST",
// the url to the service -
url: "url",
// the format that the data should be in when
// it is returned
contentType: "json",
data: '{"Id": "3"}',
// the function that executes when the server
// responds to this ajax request successfully
success: function(data) {
// put the JSON response in the employees table
}
According to the ajax api documentation the default content type is 'application/x-www-form-urlencoded'. When sending JSON, the content type should be 'application/json; charset=utf-8' except that WCF does not like that. I got the same error messages and when I removed the content type I stopped getting this error. By the way, I noticed that you set crossDomain to true, this other question is relevant to that option.

Resources