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:
OPTION
request to the target URLOPTIONS
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With