javascript
  • json
  • arcgis
  • 2016-07-25 86 views 1 likes 
    1

    我試圖從ArcGIS Online服務使用Javascript獲取令牌。但是,它總是返回一個錯誤,指示未指定client_id。JSON始終返回「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":[]}} 
    

    回答

    1

    我能夠檢索使用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請求時輸入請求標題:

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

    ,當然正確格式化爲application/x-www-form-urlencoded而不是JSON。在我的測試中,這個端點不支持JSON有效載荷。

    不幸的是,從它的外觀來看,令牌端點不支持在其CORS策略中設置Content-Type請求標頭,這意味着您在使用javascript調用它時可能會運氣不好。除了their documentation沒有提及任何有關javascript作爲支持的語言。

    所以基本上如果你想做這個工作,你可以在你的服務器端獲得訪問令牌並將它傳遞給客戶端。

    +0

    在console.log中的預檢響應中,帶回了'請求標頭字段'Content-type不被允許通過Access-Control-Allow-Headers。 – user25730

    +0

    對不起,仍然回來'client_id未指定'錯誤。 – user25730

    +0

    是的,仍然有同樣的錯誤。無論如何感謝 - 將它標記爲答案。看起來我必須重新評估我使用的方法,並更多地瞭解如何使用node.js – user25730

    相關問題