Web Services 发送XMLHttpRequest时出现CORS问题

afdcj2ne  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(248)

铬警告:
我尝试向外部Rest API发送一个http请求,但我使用了CORS策略。
我在Chrome中停用了Chrome CORS策略,在此窗口中一切正常,但在正常的Chrome窗口中,我会出现此错误:

CORS原则已封锁从来源'null'存取位于'https:///search/fi'的XMLHttpRequest:对预检请求的响应未通过访问控制检查:“Access-Control-Allow-Origin”标头的值“https://*. de”不等于提供的来源。

这里是我的代码:

<body>
  <h1>Tes Request</h1>
  <script>
  window.addEventListener("load", () => test(), false);

async function test() {
    
        return new Promise(
            resolve => {
                var req = new XMLHttpRequest();
                req.open('POST','https://Test/v1.0/', true);
                req.setRequestHeader("Authorization", "Basic " + btoa('Test'+":"+'Test'));
                req.setRequestHeader('Accept', 'application/json');
                req.setRequestHeader('Content-type', 'application/ecmascript');
                req.setRequestHeader('Access-Control-Allow-Methods','*');
                req.setRequestHeader('Access-Control-Allow-Origin', 'https://Test');
                req.onreadystatechange = function() {
                    if (this.readyState === 4) {
                        req.onreadystatechange = null;
                        if (this.status === 200) {
                            var results = JSON.parse(this.response).value;

                            resolve(results);
                        }
                        else {
                            alert(Error);
                        }
                    }
                };
        var data = `
        {
    "search": {
    "firma": {
    "ustid": "Test"
    }
    },
    "config": {
     "page":1   
    }
    }
    `;      req.withCredentials = true;
            req.send(data);
            });
    }

  </script>
</body>



Access-Control-Allow-Origin: https://app.neugeschaeft.de
Access-Control-Allow-Headers: Content-Type, Authorization, Set-Cookie, Cache-Control
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS
Access-Control-Allow-Credentials: true
4bbkushb

4bbkushb1#

您是否可以检查浏览器的调试控制台并检查网络活动以查看您的请求。请检查您是否将请求中的源设置为所需的源。然后,响应需要包含Access-Control-Allow-Origin,表明允许源访问资源。

相关问题