2016-12-11 5 views
0

Ich mache etwas Code in Javascript und ich beabsichtige, eine Methode zu tun, die eine Anfrage an eine Web-API senden und erhalten ein Token im Gegenzug (noch nicht fertig).Ajax Request Unsupported_grant_type

Dies ist mein Code

$.ajax({ 
    type: 'POST', 
    crossDomain: true, //For cors on web api 
    crossOrigin: true, 
    xhrFields: { 
     withCredentials: true, //send the credentials 
    }, 
    contentType: 'application/x-www-form-urlencoded', 
    url: 'https://localhost:44123/Token', 
    grant_type: 'password', 
    username: username, 
    password: password, 
    success: function() { 
     alert("success"); 
    }, 
    error: function (xhr, ajaxOptions, thrownError) { //Add these parameters to display the required response 
     alert(xhr.status); 
     alert(xhr.responseText); 
    }, 
}); 

Aber jedes Mal ausführen ich die Methode erhalte ich folgende Fehler:

Fehler 400 (Post) -> unsupported_grant_type

Ich bin nicht gewohnt Ajax/Js ... so bin ich ein bisschen verloren .. Irgendwelche Ideen? -

Antwort

1

Sie müssen grant_type passieren, username und password als Teil Ihrer POST-Parameter und nicht als $.ajax Parameter, wie Sie derzeit tun.

Versuchen Sie folgendes:

var body = { 
    grant_type: 'password', 
    username: username, 
    password: password 
}; 

$.ajax({ 
    url: 'https://localhost:44123/Token', 
    type: 'POST', 
    dataType: 'json', 
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8', 
    /* data: JSON.stringify(body), /* wrong */ 
    data: body, /* right */ 
    complete: function(result) { 
     //called when complete 
     alert(result); 
    }, 

    success: function(result) { 
     //called when successful 
     alert(result); 
    }, 

    error: function(result) { 
     //called when there is an error 
     alert(result); 
    }, 
}); 

Hope this helps ...

+1

Problem gelöst! Danke für die Erklärung und deine Zeit @IzzEps. Ich werde akzeptieren Sie als die richtige Antwort. – Joseph