I am trying to make an async AJAX call using JQuery.
try
{
let resp = await $.ajax({
type: 'POST',
dataType: 'json',
url: 'https://xxxx/api/token',
data: { AuthCode: authCode }
});
let accessToken = resp.access_token;
document.getElementById("token").innerText = accessToken;
} catch (ex) {
// Write the exception to the output area
document.getElementById("token")
.innerText = JSON.stringify(ex, null, 3);
}
For some reason this code is causing the following exception:
{
"readyState": 4,
"responseText": "{\"\":[\"The input was not valid.\"]}",
"responseJSON": {
"": [
"The input was not valid."
]
},
"status": 400,
"statusText": "Bad Request"
}
When I call the exact same API from Postman it returns a result with no problem.
1 Answer 1
You're probably not POSTing to your endpoint with the right headers. Does your endpoint expect application/x-www-form-urlencoded or application/json? Either way, you can set the headers via the headers property like:
$.ajax({
...
headers: {
"Content-Type":"application/json"
}
});
answered Mar 5, 2019 at 0:36
Adam Jenkins
56.3k13 gold badges85 silver badges114 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
daremachine
agree with @Adam. I think Postman has any default headers but in jquery I hat to setup.
James
@Adam, yep, that did the trick. I can't believe I missed that.
lang-js