JSON 总是返回 "client_id not specified"

JSON always returning "client_id not specified"

我正在尝试使用 Javascript 从 ArcGIS Online 服务获取令牌。但是,它总是返回一个错误,表明未指定 client_id。

我这里的一切都在做吗?

<script type="text/javascript">
    var MyJSONText = '{"client_id":"<<MY_CLIENT_ID>>","client_secret":"<<MY_CLIENT_SECRET>>","grant_type":"client_credentials","expiration":"1440","f":"json"}';
    var MyJSON = JSON.parse(MyJSONText);
    xhr = new XMLHttpRequest();
    xhr.open("POST", "https://www.arcgis.com/sharing/rest/oauth2/token/");
    xhr.send(MyJSON);
    xhr.onreadystatechange = function ()
    {
        if (xhr.readyState == 4 && xhr.status == 200)
        {
            alert(xhr.responseText);
        }
    }

</script>

编辑 - 完整错误是:

{"error":{"code":400,"error":"invalid_request","error_description":"client_id not specified","message":"client_id not specified","details":[]}}

我能够使用 application/x-www-form-urlencoded 请求检索访问令牌:

POST https://www.arcgis.com/sharing/rest/oauth2/token HTTP/1.1
User-Agent: Fiddler
Content-Type: application/x-www-form-urlencoded
Host: www.arcgis.com
Content-Length: 126

client_id=<YOUR ID>&client_secret=<YOUR SECRET>&grant_type=client_credentials&expiration=1440&f=json

这意味着您可能需要在发出 XHR 请求时指定 Content-Type 请求 header:

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

当然还有将 body 正确格式化为 application/x-www-form-urlencoded 而不是 JSON。在我的测试中,此端点不适用于 JSON 有效负载。

不幸的是,从它的外观来看,令牌端点不支持在其 CORS 策略中设置 Content-Type 请求 header,这意味着您可能无法通过 [= 调用它32=]。除了 their documentation 没有提到任何关于 javascript 作为支持语言的事情。

所以基本上,如果您想完成这项工作,您可以在服务器端获取访问令牌并将其传递给客户端。

访问令牌生成Url =>https://www.arcgis.com/sharing/rest/oauth2/token

Headers enter image description here

对于 body 在 Post man select 'x-www-form-urlencoded'

中的案例

enter image description here

之后你会得到相应的带有token的预期结果

{"access_token":"S-z3mxAqsZBeihx8NgFmNGsZAUGfzKZWCYVV2TiQO422u9XDLTCTZAkpoecyxx_LAc71I_tPkeeOlo2Pzkapv01bBOA03SzMRjRMOm-h3ljTl-pb3XdffoyYjCflE4F8LD377DbpjDWkupkdTaxJpg..","expires_in":7200}