测试javascript web应用程序-401(未经授权)错误

测试javascript web应用程序-401(未经授权)错误,javascript,outlook,office365,office-app,Javascript,Outlook,Office365,Office App,我一直在努力理解链接中给出的示例: 我为outlook创建了office应用程序,以访问office 365 outlook API 我已经使用Napa开发工具创建了这个应用程序 我得到的错误是 无法加载XMLHttpRequest。请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“”。响应的HTTP状态代码为401。-当不允许CORS时,我会出现此错误 GET 401(未经授权)-我在启用CORS时出现此错误 如何使用Outlook REST

我一直在努力理解链接中给出的示例:

我为outlook创建了office应用程序,以访问office 365 outlook API

我已经使用Napa开发工具创建了这个应用程序

我得到的错误是

  • 无法加载XMLHttpRequest。请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“”。响应的HTTP状态代码为401。-当不允许CORS时,我会出现此错误

  • GET 401(未经授权)-我在启用CORS时出现此错误

  • 如何使用Outlook REST API调用并在本地测试应用程序

    非常感谢您的帮助!谢谢

    编辑: 修改了带有注释“//changed”的代码以使示例正常工作-

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>O365 CORS Sample</title>
    <style>
    body {
        font-family:'Segoe UI';
    }
    
    .paddedElement {
        margin-top: 5px;
    }
    
    .hidden {
    visibility: hidden;
    }
    </style>
    </head>
    <body>
    <h2>O365 CORS Sample</h2>
    <label for="TxtOauthToken">OAuth Token:</label>
    <input type="text" id="TxtOauthToken" size="80" />
    <br />
    <label for="endpointUrl">Endpoint URL:</label>
    <input type="text" id="endpoint" size="80" />
    <br />
    <input type="button" class="paddedElement" id="getToken" value="Get Token">
    <input type="button" class="paddedElement" id="doCors" value="Make CORS Request" visibility="hidden" />
    <br />
    <br />
    <label for="results" class="hidden paddedElement" id="resultHeading">Results:</label>
    <br />
    <label id="debugMessage"></label>
    <pre id="results"></pre>
    <script type="text/javascript">
    (function (window) {
     var isCorsCompatible = function() {
     try
     {
     var xhr = new XMLHttpRequest();
     xhr.open("GET", getEndpointUrl());
     xhr.setRequestHeader("authorization", "Bearer " + token);
     xhr.setRequestHeader("accept", "application/json");
     xhr.onload = function () {
     // CORS is working.
     console.log("Browser is CORS compatible.");
     }
     xhr.send();
     }
     catch (e)
     {
     if (e.number == -2147024891)
     {
     console.log("Internet Explorer users must use Internet Explorer 11 with MS15-032: Cumulative security update for Internet Explorer (KB3038314) installed for this sample to work.");
     }
     else
     {
         console.log("An unexpected error occurred. Please refresh the page.");
     }
    
     }
     };
    
     var urlParameterExtraction = new (function () {
             function splitQueryString(queryStringFormattedString) {
             console.log("Query: " + queryStringFormattedString);
             var split = queryStringFormattedString.split('&');
    
             // If there are no parameters in URL, do nothing.
             if (split == "") {
             return {};
             }
    
             var results = {};
    
             // If there are parameters in URL, extract key/value pairs.
             for (var i = 0; i < split.length; ++i) {
             var p = split[i].split('=', 2);
             if (p.length == 1)
             results[p[0]] = "";
             else
             results[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
             }
    
             return results;
             }
    
             // Split the query string (after removing preceding '#').
             this.queryStringParameters = splitQueryString(window.location.hash.substr(1));
     })();
    
     var token = urlParameterExtraction.queryStringParameters['access_token'];
    
     if (token == undefined) {
         document.getElementById("TxtOauthToken").value = "Click \"Get Token\" to trigger sign-in after entering the endpoint you want to use.";
    
         document.getElementById("doCors").style.visibility = "hidden";
     }
     else {
         document.getElementById("TxtOauthToken").value = token;
         document.getElementById("doCors").style.visibility = "visible";
         document.getElementById("getToken").style.display = "none";
     }
    
     // Constructs the authentication URL and directs the user to it.
     function requestToken() {
         // Change clientId and replyUrl to reflect your app's values
         // found on the Configure tab in the Azure Management Portal.
         var clientId    = 'd18f9842-eec8-4d81-93e4-24ced3d59199';   //Changed
         var replyUrl    = 'https://localhost:8080/echo';  //Changed
             var resource    = "https://graph.windows.net/"; //Changed
    
         var authServer  = 'https://login.windows.net/common/oauth2/authorize?';
             //var endpointUrl = getEndpointUrl();
             var endpointUrl = 'http://outlook.office365.com/api/v1.0/me/messages';  //Changed
    
         var responseType = 'token';
    
         var url = authServer +
             "response_type=" + encodeURI(responseType) + "&" +
             "client_id=" + encodeURI(clientId) + "&" +
             "resource=" + encodeURI(resource) + "&" +
             "redirect_uri=" + encodeURI(replyUrl);
    
         window.location = url;
     }
    
     document.getElementById("getToken").onclick = requestToken;
    
     function getEndpointUrl() {
         return document.getElementById("endpoint").value;
     }
    
     function getFilesFromO365() {
         document.getElementById("results").textContent = "";
    
         // Check browser compatbility. Check console output for details.
         isCorsCompatible();
    
         try
         {
             var xhr = new XMLHttpRequest();
             xhr.open("GET", getEndpointUrl());
    
             // The APIs require an OAuth access token in the Authorization header, formatted like this: 'Authorization: Bearer <token>'.
             xhr.setRequestHeader("Authorization", "Bearer " + token);
    
             // Process the response from the API.
             xhr.onload = function () {
                 document.getElementById("resultHeading").style.visibility = "visible";
    
                 if (xhr.status == 200) {
                     var formattedResponse = JSON.stringify(JSON.parse(xhr.response), undefined, 2);
                     document.getElementById("results").textContent = formattedResponse;
                 } else {
                     document.getElementById("results").textContent = "HTTP " + xhr.status + "<br>" + xhr.response;
                 }
             }
    
             // Make request.
             xhr.send();
         }
         catch (err)
         {
             document.getElementById("resultHeading").style.visibility = "visible";
             document.getElementById("results").textContent = "Exception: " + err.message;
         }
     }
    
     document.getElementById("doCors").onclick = getFilesFromO365;
    
    })(window);
    </script>
    </body>
    
    </html>
    
    
    O365 CORS样品
    身体{
    字体系列:'SegoeUI';
    }
    帕德莱恩先生{
    边缘顶部:5px;
    }
    .隐藏{
    可见性:隐藏;
    }
    O365 CORS样品
    OAuth令牌:
    
    端点URL:


    结果:
    (功能(窗口){ var isCorsCompatible=函数(){ 尝试 { var xhr=new XMLHttpRequest(); open(“GET”,getEndpointUrl()); xhr.setRequestHeader(“授权”、“承载人”+令牌); setRequestHeader(“接受”、“应用程序/json”); xhr.onload=函数(){ //CORS正在工作。 log(“浏览器与CORS兼容。”); } xhr.send(); } 捕获(e) { 如果(e.number==-2147024891) { console.log(“Internet Explorer用户必须使用安装了MS15-032:Internet Explorer(KB3038314)的Internet Explorer 11,才能使此示例正常工作。”); } 其他的 { log(“发生意外错误。请刷新页面。”); } } }; var urlParameterExtraction=new(函数(){ 函数拆分QueryString(queryStringFormattedString){ log(“查询:+queryStringFormattedString”); var split=queryStringFormattedString.split('&'); //如果URL中没有参数,则不执行任何操作。 如果(拆分==“”){ 返回{}; } var结果={}; //如果URL中有参数,则提取键/值对。 对于(变量i=0;i“+xhr.response; } } //提出请求。 xhr.send(); } 捕捉(错误) { document.getElementById(“结果编码”).style.visibility=“可见”; document.getElementById(“结果”).textContent=“异常:”+err.message; } } document.getElementById(“doCors”).onclick=getFilesFromO365; })(窗口);
    您尝试遵循的示例不是外接程序,而是使用Office 365 API的JavaScript web应用程序。我相信有一个使用Office 365 API的插件是可能的,但下面的示例并不是这样做的

    在任何情况下,您得到的401都可以通过设置t来修复