0

I'm trying to translate one of my powershell scripts which makes an API call, into javascript or jquery for a chrome extension. I'm not very versed in Jquery, so I'm getting an error 415 when making a call with the below code, unsupported media type. I think I have to tell it I'm using "Content-Type","application/json"... but I'm not doing this in my powershell script untile subsequent calls after I've already gotten my token, so I'm a little confused. Why am I getting a 415 error and how do I fix it?

var token
var userName = "userID"; 
var passWord = "PaSSwOrD"; 
var tokenURL = "https://55.55.55.55/api/v1/token";  
var xhr = new XMLHttpRequest();

var data =
'&grant_type=password';
'&server_host=55.55.55.55' +
'&username=' + userName +
'&password=' + passWord;
var dataFinal = encodeURI(data);

xhr.open('POST', tokenURL, true);
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4) {
        //do something
    }
}
xhr.send(data);
alert(xhr.responseText);
shadow2020
  • 1,315
  • 1
  • 8
  • 30

1 Answers1

1

Try this (if we talk about jQuery):

var obj = null
$.ajax({
    url: "https://55.55.55.55/api/v1/token",
    method: 'POST',
    async: false,
    data: {
        grant_type: 'password',
        server_host: '55.55.55.55',
        username: 'userID',
        password: 'PaSSwOrD'
    },
    headers: {
        'Content-type': 'application/x-www-form-urlencoded',
        Accept:'application/json'
    },
    success: function(data){
    obj = data    // here the result
    }
})
console.log(obj) // here the result because of "async: false"
Oleg S
  • 311
  • 1
  • 6
  • This works, but I want to fully understand what I did. I didn't format my data correctly it looks like and I didn't tell it I was using application/json. Is the the crux of what I did wrong? I was not actually able to use async:false but what I have is working to get me my token! Thank you! – shadow2020 Dec 07 '21 at 20:18
  • 1
    It depends on API implementation, earlier you provided a link to API documentation, if you look at the document, you will see example of request, and there are two headers to send: Content-type and Accept. In your code you didn't send any headers. And API can reject this request without correct headers – Oleg S Dec 07 '21 at 20:43