【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource. 401 error请求的资源上不存在“Access-Control-Allow-Origin”标头。 401 错误
【发布时间】:2016-11-25 22:14:02
【问题描述】:

我一直在尝试使用 bing 拼写检查 API 来实现拼写检查。我收到 401 错误。错误是

请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'null' 不允许访问。响应的 HTTP 状态代码为 401。

    <html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

<script type="text/javascript">
    function hi(){


        var params = {
            // Request parameters
            "mode": "{Spell}",
        };

        $.ajax({
             url: "https://api.cognitive.microsoft.com/bing/v5.0/spellcheck/?" + $.param(params),
             beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{0c6cb56a997b41d4958ace895a677729}");
            },
        crossDomain: false,
        headers: {'X-Requested-With': 'XMLHttpRequest'},
        type: "POST",
        dataType: 'jsonp',

            // Request body
                data: {
            dataSpell: $("#textContent").val()},

        success : function(result){
            $("div").html(result); }
        //dataType: 'jsonp'
    });


    }
</script>

</head>
<body>
<textarea rows="4" cols="50" id="textContent" spell-check="true" placeholder="Type here"></textarea>
<button type="button" id="spellcheck" onclick="hi();" >Click Me!</button>
<div> </div>
</body>

</html>​

【问题讨论】:

  • 您不能从另一个网站的 webscript 向一个网站发送请求,除非第三方网站明确将您列入白名单。你应该阅读Cross Domain Resource Sharing (CORS)

标签: javascript jquery html api spell-checking


【解决方案1】:

{...} 您正在向与您的页面所在的域不同的域执行 XMLHttpRequest。因此浏览器会阻止它,因为出于安全原因,它通常允许同一来源的请求。当你想要做一个跨域请求时,你需要做一些不同的事情。

引用this thread 的答案,如果您仍然对为什么会收到此错误感到困惑,请查看它。您可以在此处了解如何使用CORS 绕过此问题。

【讨论】:

    猜你喜欢
    • 2015-07-29
    • 1970-01-01
    • 2017-12-16
    • 2015-04-04
    • 1970-01-01
    • 2020-11-08
    • 2013-11-29
    • 2014-07-28
    相关资源
    最近更新 更多