Ajax 请求 Unsupported_grant_type

Ajax Request Unsupported_grant_type

我正在 javascript 中编写一些代码,我打算执行一种向 Web api 发送请求并在 return 中接收令牌的方法(尚未完成).

这是我的代码

 $.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(Post) --> unsupported_grant_type

我不习惯ajax/js ...所以我有点迷路了..有什么想法吗? -

您需要将 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);
    },
});

希望这对您有所帮助...