Origin is not allowed by Access-Control-Allow-Origin
I wrote an article on this issue a while back, Cross Domain AJAX.
The easiest way to handle this if you have control of the responding server is to add a response header for:
Access-Control-Allow-Origin: *
This will allow cross-domain Ajax. In PHP, you'll want to modify the response like so:
<?php header('Access-Control-Allow-Origin: *'); ?>
You can just put the Header set Access-Control-Allow-Origin *
setting in the Apache configuration or htaccess file.
It should be noted that this effectively disables CORS protection, which very likely exposes your users to attack. If you don't know that you specifically need to use a wildcard, you should not use it, and instead you should whitelist your specific domain:
<?php header('Access-Control-Allow-Origin: http://example.com') ?>
Origin origin is not allowed by Access-Control-Allow-Origin
Since they are running on different ports, they are different JavaScript origin
. It doesn't matter that they are on the same machine/hostname.
You need to enable CORS on the server (localhost:8080). Check out this site: http://enable-cors.org/
All you need to do is add an HTTP header to the server:
Access-Control-Allow-Origin: http://localhost:3000
Or, for simplicity:
Access-Control-Allow-Origin: *
Thought don't use "*" if your server is trying to set cookie and you use withCredentials = true
when responding to a credentialed request, server must specify a domain, and cannot use wild carding.
You can read more about withCredentials
here
Origin is not allowed by Access-Control-Allow-Origin' since 2021
We have fixed the issue. you will get "access-control-allow-origin: *" header at the API responses.
your API key (Ocp-Apim-Subscription-Key) is private information, and you should not expose it at the client side.
you should generate access token from your web server using that key and use (send it at Authorization header) it with all your operations request.
please delete it from the example above as well.
Why does my JavaScript code receive a No 'Access-Control-Allow-Origin' header is present on the requested resource error, while Postman does not?
If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request.
When you are using Postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
This answer covers a lot of ground, so it’s divided into three parts:
- How to use a CORS proxy to avoid “No Access-Control-Allow-Origin header” problems
- How to avoid the CORS preflight
- How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems
How to use a CORS proxy to avoid “No Access-Control-Allow-Origin header” problems
If you don’t control the server your frontend code is sending a request to, and the problem with the response from that server is just the lack of the necessary Access-Control-Allow-Origin
header, you can still get things to work—by making the request through a CORS proxy.
You can easily run your own proxy with code from https://github.com/Rob--W/cors-anywhere/.
You can also easily deploy your own proxy to Heroku in just 2-3 minutes, with 5 commands:
git clone https://github.com/Rob--W/cors-anywhere.git
cd cors-anywhere/
npm install
heroku create
git push heroku master
After running those commands, you’ll end up with your own CORS Anywhere server running at, e.g., https://cryptic-headland-94862.herokuapp.com/
.
Now, prefix your request URL with the URL for your proxy:
https://cryptic-headland-94862.herokuapp.com/https://example.com
Adding the proxy URL as a prefix causes the request to get made through your proxy, which:
- Forwards the request to
https://example.com
. - Receives the response from
https://example.com
. - Adds the
Access-Control-Allow-Origin
header to the response. - Passes that response, with that added header, back to the requesting frontend code.
The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin
response header is what the browser sees.
This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS
request, because in that case, the proxy also sends the Access-Control-Allow-Headers
and Access-Control-Allow-Methods
headers needed to make the preflight succeed.
How to avoid the CORS preflight
The code in the question triggers a CORS preflight—since it sends an Authorization
header.
https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
Even without that, the Content-Type: application/json
header will also trigger a preflight.
What “preflight” means: before the browser tries the POST
in the code in the question, it first sends an OPTIONS
request to the server, to determine if the server is opting-in to receiving a cross-origin POST
that has Authorization
and Content-Type: application/json
headers.
It works pretty well with a small curl script - I get my data.
To properly test with curl
, you must emulate the preflight OPTIONS
the browser sends:
curl -i -X OPTIONS -H "Origin: http://127.0.0.1:3000" \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: Content-Type, Authorization' \
"https://the.sign_in.url"
…with https://the.sign_in.url
replaced by whatever your actual sign_in
URL is.
The response the browser needs from that OPTIONS
request must have headers like this:
Access-Control-Allow-Origin: http://127.0.0.1:3000
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type, Authorization
If the OPTIONS
response doesn’t include those headers, the browser will stop right there and never attempt to send the POST
request. Also, the HTTP status code for the response must be a 2xx—typically 200 or 204. If it’s any other status code, the browser will stop right there.
The server in the question responds to the OPTIONS
request with a 501 status code, which apparently means it’s trying to indicate it doesn’t implement support for OPTIONS
requests. Other servers typically respond with a 405 “Method not allowed” status code in this case.
So you’ll never be able to make POST
requests directly to that server from your frontend JavaScript code if the server responds to that OPTIONS
request with a 405 or 501 or anything other than a 200 or 204 or if doesn’t respond with those necessary response headers.
The way to avoid triggering a preflight for the case in the question would be:
- if the server didn’t require an
Authorization
request header but instead, e.g., relied on authentication data embedded in the body of thePOST
request or as a query param - if the server didn’t require the
POST
body to have aContent-Type: application/json
media type but instead accepted thePOST
body asapplication/x-www-form-urlencoded
with a parameter namedjson
(or whatever) whose value is the JSON data
How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems
I am getting another error message:
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://127.0.0.1:3000
' is therefore not allowed
access. The credentials mode of requests initiated by the
XMLHttpRequest is controlled by the withCredentials attribute.
For requests that have credentials, browsers won’t let your frontend JavaScript code access the response if the value of the Access-Control-Allow-Origin
header is *
. Instead the value in that case must exactly match your frontend code’s origin, http://127.0.0.1:3000
.
See Credentialed requests and wildcards in the MDN HTTP access control (CORS) article.
If you control the server you’re sending the request to, a common way to deal with this case is to configure the server to take the value of the Origin
request header, and echo/reflect that back into the value of the Access-Control-Allow-Origin
response header; e.g., with nginx:
add_header Access-Control-Allow-Origin $http_origin
But that’s just an example; other (web) server systems have similar ways to echo origin values.
I am using Chrome. I also tried using that Chrome CORS Plugin
That Chrome CORS plugin apparently just simplemindedly injects an Access-Control-Allow-Origin: *
header into the response the browser sees. If the plugin were smarter, what it would be doing is setting the value of that fake Access-Control-Allow-Origin
response header to the actual origin of your frontend JavaScript code, http://127.0.0.1:3000
.
So avoid using that plugin, even for testing. It’s just a distraction. To test what responses you get from the server with no browser filtering them, you’re better off using curl -H
as above.
As far as the frontend JavaScript code for the fetch(…)
request in the question:
headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');
Remove those lines. The Access-Control-Allow-*
headers are response headers. You never want to send them in requests. The only effect of that is to trigger a browser to do a preflight.
How does the 'Access-Control-Allow-Origin' header work?
Access-Control-Allow-Origin is a CORS (cross-origin resource sharing) header.
When Site A tries to fetch content from Site B, Site B can send an Access-Control-Allow-Origin response header to tell the browser that the content of this page is accessible to certain origins. (An origin is a domain, plus a scheme and port number.) By default, Site B's pages are not accessible to any other origin; using the Access-Control-Allow-Origin header opens a door for cross-origin access by specific requesting origins.
For each resource/page that Site B wants to make accessible to Site A, Site B should serve its pages with the response header:
Access-Control-Allow-Origin: http://siteA.com
Modern browsers will not block cross-domain requests outright. If Site A requests a page from Site B, the browser will actually fetch the requested page on the network level and check if the response headers list Site A as a permitted requester domain. If Site B has not indicated that Site A is allowed to access this page, the browser will trigger the XMLHttpRequest
's error
event and deny the response data to the requesting JavaScript code.
Non-simple requests
What happens on the network level can be slightly more complex than explained above. If the request is a "non-simple" request, the browser first sends a data-less "preflight" OPTIONS request, to verify that the server will accept the request. A request is non-simple when either (or both):
- using an HTTP verb other than GET or POST (e.g. PUT, DELETE)
- using non-simple request headers; the only simple requests headers are:
Accept
Accept-Language
Content-Language
Content-Type
(this is only simple when its value isapplication/x-www-form-urlencoded
,multipart/form-data
, ortext/plain
)
If the server responds to the OPTIONS preflight with appropriate response headers (Access-Control-Allow-Headers
for non-simple headers, Access-Control-Allow-Methods
for non-simple verbs) that match the non-simple verb and/or non-simple headers, then the browser sends the actual request.
Supposing that Site A wants to send a PUT request for /somePage
, with a non-simple Content-Type
value of application/json
, the browser would first send a preflight request:
OPTIONS /somePage HTTP/1.1
Origin: http://siteA.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type
Note that Access-Control-Request-Method
and Access-Control-Request-Headers
are added by the browser automatically; you do not need to add them. This OPTIONS preflight gets the successful response headers:
Access-Control-Allow-Origin: http://siteA.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type
When sending the actual request (after preflight is done), the behavior is identical to how a simple request is handled. In other words, a non-simple request whose preflight is successful is treated the same as a simple request (i.e., the server must still send Access-Control-Allow-Origin
again for the actual response).
The browsers sends the actual request:
PUT /somePage HTTP/1.1
Origin: http://siteA.com
Content-Type: application/json
{ "myRequestContent": "JSON is so great" }
And the server sends back an Access-Control-Allow-Origin
, just as it would for a simple request:
Access-Control-Allow-Origin: http://siteA.com
See Understanding XMLHttpRequest over CORS for a little more information about non-simple requests.
Why am I seeing an origin is not allowed by Access-Control-Allow-Origin error here?
Javascript is limited when making ajax requests outside of the current domain.
- Ex 1: your domain is example.com and you want to make a request to test.com => you cannot.
- Ex 2: your domain is example.com and you want to make a request to inner.example.com => you cannot.
- Ex 3: your domain is example.com:80 and you want to make a request to example.com:81 => you cannot
- EX 4: your domain is example.com and you want to make a request to example.com => you can.
Javascript is limited by the "same origin policy" for security reasons so that a malicious script cannot contact a remote server and send sensitive data.
jsonp is a different way to use javascript. You make a request and results are encapsulated into a callback function which is run in the client. It's the same as linking a new script tag into the head part of your html (you know that you can load scripts from different domains than yours here).
However, to use jsonp the server must be configured properly. If this is not the case you cannot use jsonp and you MUST rely on a server side proxy (PHP, ASP, etc.). There are plenty of guides related to this topic, just google it!
Angularjs / sailsjs :Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers
Ok I finally found the issue.
I compared the response and request headers with interceptor and with it.
I change my code as below and it works.
In app.js of angularjs
I commented all the headers part.
//Enable cross domain calls
/* $httpProvider.defaults.useXDomain = true;
//Remove the header used to identify ajax call that would prevent CORS from working
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = 'origin, content-type, accept';
$httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
$httpProvider.defaults.headers.common['Access-Control-Allow-Methods'] = 'GET,POST,PUT,HEAD,DELETE,OPTIONS';*/
$httpProvider.interceptors.push('TokenInterceptor');
And in my sails.js cors setup config I commented methods and headers. And it works well.
module.exports.cors = {
/***************************************************************************
* *
* Allow CORS on all routes by default? If not, you must enable CORS on a *
* per-route basis by either adding a "cors" configuration object to the *
* route config, or setting "cors:true" in the route config to use the *
* default settings below. *
* *
***************************************************************************/
allRoutes: true,
/***************************************************************************
* *
* Which domains which are allowed CORS access? This can be a *
* comma-delimited list of hosts (beginning with http:// or https://) or *
* "*" to allow all domains CORS access. *
* *
***************************************************************************/
origin: '*',
/***************************************************************************
* *
* Allow cookies to be shared for CORS requests? *
* *
***************************************************************************/
credentials: true
/***************************************************************************
* *
* Which methods should be allowed for CORS requests? This is only used in *
* response to preflight requests (see article linked above for more info) *
* *
***************************************************************************/
// methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
/***************************************************************************
* *
* Which headers should be allowed for CORS requests? This is only used in *
* response to preflight requests. *
* *
***************************************************************************/
// headers: 'origin, content-type, accept'
};
Related Topics
How to Implement a Stack and a Queue in JavaScript
How to Find the Array Index with a Value
How to Force Angular2 to Post Using X-Www-Form-Urlencoded
Limited Parallelism with Async/Await in Typescript/Es7
How to Solve 'Redirect Has Been Blocked by Cors Policy: No 'Access-Control-Allow-Origin' Header'
How to Run HTML Files Directly from Github, Instead of Just Viewing Their Source
HTML "Data-" Attribute as JavaScript Parameter
"Pointer-Events: None" Does Not Work in IE9 and Ie10
Sending Message to a Specific Connected Users Using Websocket
Force Page Zoom at 100% with Js
Convert Character to Ascii Code in JavaScript
Expose Jquery to Real Window Object with Webpack
Javascript/Jquery: Test If Window Has Focus
Completely Removing Duplicate Items from an Array
Javascript: Using a Condition in Switch Case
How to Develop Desktop Apps Using HTML/Css/Javascript