I copied and paste a JavaScript code snippet from Postman into my HTML page. I have to enter a email and password, and then the userToken that is generated from another function will be passed into this function below.
The previous function was fine, but I then get this error: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.
How can I fix this problem?
<html>
<head>
<link rel="stylesheet" href="Default.css">
</head>
<body>
<script language = "javascript" type = "text/javascript">
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("userToken", "[---------------]");
myHeaders.append("Cookie", ".AspNetCore.Session=[---------]");
var raw = JSON.stringify({
"time": 0
});
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("[------].com", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
</script>
</html>
Do note that userToken, the URL, and the cookie is confidential.
The issue isn’t the fetch vs AJAX… it is CORS and the headers from the request in the browser and response on the server. Read the article I linked to. It still applies here.
Is the domain you’re trying to fetch from owned by you?
If not, then it’s impossible to fetch data from it with javascript - this is not allowed by the CORS policies, as @Martyr2 stated above. By default, asynchronous requests are allowed only for scripts hosted on the same domain.
If yes, learn how to disable CORS for your web server. It requires some configuration to make web server send required CORS headers.
I do not own this domain. The domain is owned by another party, and my role is to grab data from the API to my little site, so there’s no way I can disable the CORS myself =(
So you mean there is no way whatsoever to get my data for this case, unless I go for asynchronous request? Or I have to contact the engineers over there?
CORS won’t allow you to make requests from browser but you still can consume their API using HTTP-requests from your backend.
In most cases, problem may be solved using proxy backend script. Make that script to execute API requests for you and fetch data from that script - not from the target site directly.
There are many implementations around, you may google something similar for your backend language
Most APIs will not allow cross origin requests on domains other than ones controlled since doing so introduces a security major vulnerability for the owner of the API. In those cases a server-side proxy is required to communicate with the API as veocode suggested.