I use the Javascript API within an Angular Project. I'm using HTTPS connection. It all worked the last months but since last week, I don't get any Tiles loaded.
To a lot of requests, I get the response:
403 "No Access-Control-Allow-Origin header is present on the requested resource."
Sometimes the request is successful and I get a Tile and the correct cors header, but that is only 1 of 20 requests I think.
Did I miss some API changes? Is this only on my side or are there any others affected?
You can always Enable CORS by returning correct headers
Access-Control-Allow-Headers string
Access-Control-Allow-Methods string
Access-Control-Allow-Origin string
For more details -
https://developer.here.com/documentation/tour-planning/api-reference-swagger.html
https://developer.here.com/olp/documentation/vector-tiles-api/dev_guide/topics/http-response-codes.html
Related
I created an API endpoint using Google Cloud Functions and am trying to call it from a JS fetch function.
I am running into errors that I am pretty sure are related to either CORS or the output format, but I'm not really sure what is going on. A few other SO questions are similar, and helped me realize I needed to remove the mode: "no-cors". Most mention enabling CORS on the BE, so I added response.headers.set('Access-Control-Allow-Origin', '*') - which I learned of in this article - to ensure CORS would be enabled... But I still get the "Failed to fetch" error.
The Full Errors (reproducible in the live demo linked below) are:
Uncaught Error: Cannot add node 1 because a node with that id is
already in the Store. (This one is probably unrelated?)
Access to fetch at
'https://us-central1-stargazr-ncc-2893.cloudfunctions.net/nearest_csc?lat=37.75&lon=-122.5'
from origin 'https://o2gxx.csb.app' has been blocked by CORS policy:
Request header field access-control-allow-origin is not allowed by
Access-Control-Allow-Headers in preflight response.
GET
https://us-central1-stargazr-ncc-2893.cloudfunctions.net/nearest_csc?lat=37.75&lon=-122.5 net::ERR_FAILED
Uncaught (in promise) TypeError: Failed to fetch
See Code Snippets below, please note where I used <---- *** Message *** to denote parts of the code that have recently changed, giving me one of those two errors.
Front End Code:
function getCSC() {
let lat = 37.75;
let lng = -122.5;
fetch(
`https://us-central1-stargazr-ncc-2893.cloudfunctions.net/nearest_csc?lat=${lat}&lon=${lng}`,
{
method: "GET",
// mode: "no-cors", <---- **Uncommenting this predictably gets rid of CORS error but returns a Opaque object which seems to have no data**
headers: {
// Accept: "application/json", <---- **Originally BE returned stringified json. Not sure if I should be returning it as something else or if this is still needed**
Origin: "https://lget3.csb.app",
"Access-Control-Allow-Origin": "*"
}
}
)
.then(response => {
console.log(response);
console.log(response.json());
});
}
Back End Code:
import json
import math
import os
import flask
def nearest_csc(request):
"""
args: request object w/ args for lat/lon
returns: String, either with json representation of nearest site information or an error message
"""
lat = request.args.get('lat', type = float)
lon = request.args.get('lon', type = float)
# Get list of all csc site locations
with open(file_path, 'r') as f:
data = json.load(f)
nearby_csc = []
# Removed from snippet for clarity:
# populate nearby_csc (list) with sites (dictionaries) as elems
# Determine which site is the closest, assigned to var 'closest_site'
# Grab site url and return site data if within 100 km
if dist_km < 100:
closest_site['dist_km'] = dist_km
// return json.dumps(closest_site) <--- **Original return statement. Added 4 lines below in an attempt to get CORS set up, but did not seem to work**
response = flask.jsonify(closest_site)
response.headers.set('Access-Control-Allow-Origin', '*')
response.headers.set('Access-Control-Allow-Methods', 'GET, POST')
return response
return "No sites found within 100 km"
Fuller context for code snippets above:
Here is a Code Sandbox Demo of the above.
Here is the full BE code on GitHub, minus the most recent attempt at adding CORS.
The API endpoint.
I'm also wondering if it's possible that CodeSandbox does CORS in a weird way, but have had the same issue running it on localhost:3000, and of course in prod would have this on my own personal domain.
The Error would appear to be CORS-related ( 'https://o2gxx.csb.app' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.) but I thought adding response.headers.set('Access-Control-Allow-Origin', '*') would solve that. Do I need to change something else on the BE? On the FE?
TLDR;
I am getting the Errors "Failed to fetch" and "field access-control-allow-origin is not allowed by Access-Control-Allow-Headers" even after attempts to enable CORS on backend and add headers to FE. See the links above for live demo of code.
Drop the part of your frontend code that adds a Access-Control-Allow-Origin header.
Never add Access-Control-Allow-Origin as a request header in your frontend code.
The only effect that’ll ever have is a negative one: it’ll cause browsers to do CORS preflight OPTIONS requests even in cases when the actual (GET, POST, etc.) request from your frontend code would otherwise not trigger a preflight. And then the preflight will fail with this message:
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response
…that is, it’ll fail with that unless the server the request is being made to has been configured to send an Access-Control-Allow-Headers: Access-Control-Allow-Origin response header.
But you never want Access-Control-Allow-Origin in the Access-Control-Allow-Headers response-header value. If that ends up making things work, you’re actually just fixing the wrong problem. Because the real fix is: never set Access-Control-Allow-Origin as a request header.
Intuitively, it may seem logical to look at it as “I’ve set Access-Control-Allow-Origin both in the request and in the response, so that should be better than just having it in the response” — but it’s actually worse than only setting it in the response (for the reasons described above).
So the bottom line: Access-Control-Allow-Origin is solely a response header, not a request header. You only ever want to set it in server-side response code, not frontend JavaScript code.
The code in the question was also trying to add an Origin header. You also never want to try to set that header in your frontend JavaScript code.
Unlike the case with the Access-Control-Allow-Origin header, Origin is actually a request header — but it’s a special header that’s controlled completely by browsers, and browsers won’t ever allow your frontend JavaScript code to set it. So don’t ever try to.
I'm running an ionic application using ionic serve on port 8080. I do understand the preflight process and I believe I'm getting the right response:
Still, I'm getting this error:
Failed to load https://bla.bla: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:8080' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Then, the real request (GET) is not being sent.
What is even weirder is that just before this one request, I'm able to send a POST to the same server. The response headers are the same. The only difference in the request is that the Access-Control-Request-Headers is content-type instead of authentication
Any ideas?
Finally found the answer and it was my fault, not a chrome bug.
Thing is, some time ago I tried using this extension:
https://chrome.google.com/webstore/detail/cors-toggle/jioikioepegflmdnbocfhgmpmopmjkim?hl=en
And it didn't work for my needs, but I forgot to uinstall it. Turns out it was having some kind of conflict, since it seems to add an "Access-Control-Allow-Origin: *" header for every response. Thus it would conflict in a request with credentials (I'm guessing the Authentication header does that, not sure why tbh).
Anyway, after I uninstalled it, it's now working fine.
I want to get data from a JSON file for my webpage, I searched a lot and I failed to find a request that succeeds with HTTPS.
I get this error when I run the HTML file on my machine using jQuery.getJSON():
Origin null is not allowed by Access-Control-Allow-Origin.
Any ideas?
Add this header into an Apache .conf or .htaccess file
Header set Access-Control-Allow-Origin "*"
You may also need to add these:
Header set Access-Control-Allow-Methods POST, GET, OPTIONS
Header set Access-Control-Allow-Headers "X-SOME-HEADER" (additional headers you need to pass)
Header always set Access-Control-Max-Age "(number of seconds to cache results)"
Before you launch for production, you should consider restricting the origin if possible. For example, Access-Control-Allow-Origin: example.com. If the Ajax requests will come from the same server, you should remove these headers entirely when you launch.
I faced with that problem when implementing REST api with Restify secured with bearer token authorization type.
when I sending simple get request to API server it fails with CORS problem
405 (Method Not Allowed) angular.js:7962
OPTIONS http://api.host.com/tests No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'http://local.host.com' is
therefore not allowed access.
Solution described in my answer, so it's not real question for me, because I placed it when already know the answer, but hope it will save time for someone else in future.
The problem was faced because of restify has internal CORS module who manage CORS logic. in this module you could find list of allowed headers, by default it's
[
'accept',
'accept-version',
'content-type',
'request-id',
'origin',
'x-api-version',
'x-request-id'
]
As I say in the question, I use bearer token auth, so I send my request with Authorization header. It's not included in default list, and that's why my request fails.
To fix that problem we need to add this header to the list of ALLOW_HEADERS. for that in my restify configuration code I add this line:
restify.CORS.ALLOW_HEADERS.push('authorization');
Think that info could be helpfull if you faced with similar problem, because I spend a lot to find the solution.
You won't be able to access the URL http://api.host.com/tests from a file deployed at http://local.host.com due to the same-origin policy.
As the source (origin) page and the target URL are at different domains, your code is actually attempting to make a Cross-domain (CORS) request (thus the error with OPTIONS -- see the explanation below), not an ordinary GET.
In a few words, the same-origin policy enforces that browsers only allow Ajax calls to services in the same domain as the HTML page.
Example: A page in http://www.example.com/myPage.html can only directly request services that are in http://www.example.com, like http://www.example.com/testservice/etc. If the service is in other domain, the browser won't make the direct call (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a CORS request, your browser:
Will first send an OPTION request to the target URL
And then only if the server response to that OPTIONS contains the adequate headers (Access-Control-Allow-Origin is one of them) to allow the CORS request, the browse will perform the call (almost exactly the way it would if the HTML page was at the same domain).
If the expected headers don't come in the OPTIONS, the browser will give up, informing the error (that it attempted a CORS request and didn't find the necessary headers).
How to solve it?
Place the target service in the same domain of the origin page; or
Enable CORS (enable the necessary headers) on the server; or
If you don't have server-side access to the service, you could also mirror it (create a copy of it in the server you own).
JSONP is also a solution if you just want to request information (but this would require server-side access to setup as well).
I have encountered a problem that I cant resolve.
I have some js (jquery) POST soap (over PHP) request code working on Apache with Cors enabled for calling HTTPS, and it worked fine.
I've migrated to IIS7, set response headers:
Access-Control-Allow-Origin = *
Access-Control-Allow-Methods = POST`
and now strangly when sending
Content-Type: text/xml;
it is refused, but when sending a default
application/x-www-form-urlencoded
strangly I got the response (of course error response from Soap server but still, meaning that Cors works for this).
So the question is, if there is anything else to set in iis headers? I tried to find an answer for a day but with no luck. My guess is it is about Access-Control-Allow-Headers but still I cant find a valid example.
You need to set the following header:
Access-Control-Allow-Headers: Content-Type
You may also have to put other headers in that list. The best way to figure out which headers to add is to inspect the Access-Control-Request-Headers header on the request, and see what values its asking for, and then echo those values in the response above.
The reason Content-Type needs to be included in this header is because you are asking for a non-standard value ('application/x-www-form-urlencoded' is a standard value).