我正在尝试使用 Javascript 从 ArcGIS Online 服务获取 token 。但是,它总是返回一个错误,表明未指定 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
请求检索访问 token :
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');
当然还有将正文正确格式化为 application/x-www-form-urlencoded
而不是 JSON。在我的测试中,此端点不适用于 JSON 负载。
不幸的是, token 端点不支持在其 CORS 策略中设置 Content-Type
请求 header ,这意味着您可能无法使用 javascript 调用它。除了their documentation
没有提及任何有关 javascript
的支持语言。
所以基本上,如果您想完成这项工作,您可以在服务器端获取访问 token 并将其传递给客户端。
关于javascript - JSON 总是返回 "client_id not specified",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38560710/