Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

javascript - The CORS Header 'Access-Control-Allow-Origin' is missing

I'm trying to use webUntis'(docs) API for a school project. For now I'm just trying to establish any kind of connection to the API.

var result;
const url = 'https://api.webuntis.dk/api/status';
var xhr = new XMLHttpRequest();

xhr.open('GET',url, true);
xhr.setRequestHeader('Access-Control-Allow-Origin','*');
xhr.setRequestHeader('Content-type','application/json');
xhr.setRequestHeader('Access-Control-Allow-Methods','GET');
xhr.setRequestHeader('X-API-KEY', '/*API KEY*/');
xhr.send();


xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        result = xhr.responseType;
        console.log(result);
    }
};

This code produces the following error message:

Cross-Origin request blocked: The same origin policy prohibits the reading of the external resource at https://api.webuntis.dk/api/status (Reason: CORS Header 'Access-Control-Allow-Origin' is missing).

How may this problem be solved? Perhaps my API key is wrong?

Disclaimer: The error message was translated from German.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are making a request to another site, in this case the API at api.webuntis.dk. This type of request is called a "Cross Origin Request"

For such requests to work in JavaScript, the server on their end needs to allow them.

This is done by their server sending special CORS headers, the most basic one being the "Access-Control-Allow-Origin" header.

I guess the API provider has not foreseen or planned for this API to be used from a frontend (e.g. JavaScript in the browser), so you would have to work around this.

One way is to set up your own server and have the JavaScript code make a request to your server and your server then making a request to the API, as server side code is not bound to CORS headers.

Alternatively, to try things out, you can prefix the URL with https://cors.io like this:

const url = 'https://cors.io/?https://api.webuntis.dk/api/status';

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...