2016-12-11 5 views
0

私はjavascriptでいくつかのコードを実行しています。私は、Web APIにリクエストを送信し、代わりにトークンを受け取るメソッドを実行しようとしています。AjaxリクエストUnsupported_grant_type

これは私のコード

$.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); 
    }, 
}); 

ですが、毎回、私は次のエラー受け取る方法を実行します。

エラー400(ポスト) - >

unsupported_grant_type私はに慣れていませんよajax/js ...だから私は少し失われたlitleビットです..任意のアイデア? -

答えて

1

あなたのPOSTパラメータの一部としてではなく、あなたが現在行っているよう$.ajaxパラメータとしてgrant_typeusernamepasswordを渡す必要があります。

これを試してみてください。このことができます

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); 
    }, 
}); 

希望...解決

+1

問題を!説明とあなたの時間@IzzEpsをありがとう。私はあなたが正しいものとして答えることを受け入れるでしょう。 – Joseph