Jquery REST API POST call, I'm getting 415 error?

64 Views Asked by At

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);
1

There are 1 best solutions below

2
On

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"