I'm currently working on a website built with ASP.NET that requires data retrieval from CloudKit. Utilizing CloudKit JS, I successfully retrieve a record from CloudKit and aim to send the data to the server using C# in my JavaScript code. I can convert the JSON object of the retrieved record into a string with JSON.stringify(record);
, however, I'm facing difficulties in sending it to the server through AJAX. Below is the snippet of my code attempting to send the data via AJAX:
function afterRecordLoaded(record) {
var decodedRecord = JSON.stringify(record);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/receive?type=specific&" + "data=" + decodedRecord, true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send();
}
afterRecordLoaded(record);
Although I can manually perform the request correctly using the Browser Dev Tools console, when AJAX executes it, an HTTP Error 400 occurs. Essentially, typing the same URL (with correct parameters) directly into the address bar works, but when AJAX tries to do the same, it fails with an HTTP Error 400.
Below is the C# code for the page tasked with handling the incoming request:
var token = antiforgery.GetAndStoreTokens(HttpContext).RequestToken;
var type = Request.Query["type"];
var data = Request.Query["data"];
if (type == "specific")
{
if (data != "")
{
PostProcessor.processPostData(data);
}
else
{
Response.StatusCode = 400;
}
}
Upon researching, I found that others have encountered the same issue and resolved it by implementing an anti-forgery token. However, I'm unsure how to incorporate anti-forgery tokens into my code. Any guidance on resolving the HTTP Error 400 or incorporating anti-forgery tokens to address the issue would be greatly appreciated. Apologies if this question seems scattered or basic, as I am relatively new to working with ASP.NET. Thank you.