首页 > 解决方案 > 调用 REST API、JavaScript 时的 CORS 策略

问题描述

我正在尝试在 JavaScript 中调用 API,如果我在 URL 栏中编写它,它可以工作,但如果我使用我的代码,它有 CORS 策略问题。我无权访问服务器,我应该找到一种在客户端解决的方法。这是我的代码:

var xhr = new XMLHttpRequest();

    var url = 'http://api.openweathermap.org/data/2.5/weather?q=London&APPID=My-API-Key';
    xhr.open('GET', url, true);
    xhr.withCredentials = true;
    xhr.setRequestHeader("APPID", "MY API Key");
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('Origin', '*');
    //console.log(json);

    xhr.send();

    xhr.onload = function () {
        if (xhr.status != 200) {
            alert(`Error ${xhr.status}: ${xhr.statusText}`);
        } else {
            alert(`Done, got ${xhr.response.length} bytes`);
        }
    };

    xhr.onprogress = function (event) {
        if (event.lengthComputable) {
            alert(`Received ${event.loaded} of ${event.total} bytes`);
        } else {
            alert(`Received ${event.loaded} bytes`); // no Content-Length
        }

    };

    xhr.onerror = function () {
        alert("Request failed");
    };

</script>

它有错误:

从源“ https://localhost:44399 ”访问位于“ https://api.openweathermap.org/data/2.5/weather?q=London&APPID=My-API-key ”的 XMLHttpRequest已被 CORS 策略阻止:响应预检请求未通过访问控制检查:当请求的凭据模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。XMLHttpRequest 发起的请求的凭证模式由 withCredentials 属性控制。

任何人有想法如何解决这个错误?我应该将我的 Origin 或其他任何内容作为标头发送到哪里才能从服务器获得正确的响应?我应该在客户端处理它,并且我已经在标题中写了 Origin * 但仍然无法正常工作。

此致

标签: javascriptrestapicorsxmlhttprequest

解决方案


您是否尝试在服务器上使用“allow-origin: *”标头?这可能是问题的原因(您的服务器不接受这些请求)


推荐阅读