Ajax 请求 Unsupported_grant_type

Jos*_*eph 0 ajax jquery token

我正在用 javascript 编写一些代码,我打算做一个方法,将请求发送到 web api 并接收一个令牌作为回报(尚未完成)。

这是我的代码

 $.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);
    },
});
Run Code Online (Sandbox Code Playgroud)

但是每次我执行该方法时,都会收到以下错误:

错误 400(发布)--> unsupported_grant_type

我不习惯 ajax/js ......所以我有点迷茫......有什么想法吗?——

Izz*_*Eps 5

你需要传递grant_typeusernamepassword为您的POST参数的一部分,而不是作为一个$.ajax参数,你正在做的事情。

尝试这个:

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);
    },
});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助...