Mod note: This question is about why XMLHttpRequest/fetch/etc. on the browser are subject to the Same Access Policy restrictions (you get errors mentioning CORB or CORS) while Postman is not. This question is not about how to fix a "No 'Access-Control-Allow-Origin'..." error. It's about why they happen.
Please stop posting:
CORS configurations for every language/framework under the sun. Instead find your relevant language/framework's question.
3rd party services that allow a request to circumvent CORS
Command line options for turning off CORS for various browsers
I am trying to do authorization using JavaScript by connecting to the RESTful API built-in Flask. However, when I make the request, I get the following error:
XMLHttpRequest cannot load http://myApiUrl/login.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access.
I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?
This is the request code:
$.ajax({
type: 'POST',
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain: true,
xhrFields: {
withCredentials: true,
},
})
.done(function (data) {
console.log('done');
})
.fail(function (xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
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.
WARNING: Using Access-Control-Allow-Origin: * can make your API/website vulnerable to cross-site request forgery (CSRF) attacks. Make certain you understand the risks before using this code.
It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:
<?php header('Access-Control-Allow-Origin: *'); ?>
If you are using Node-red you have to allow CORS in the node-red/settings.js file by un-commenting the following lines:
// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
origin: "*",
methods: "GET,PUT,POST,DELETE"
},
If you are using Flask same as the question; you have first to install flask-cors
pip install -U flask-cors
Then include the Flask cors package in your application.
from flask_cors import CORS
A simple application will look like:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
#app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
For more details, you can check the Flask documentation.
Because
$.ajax({type: "POST" - calls OPTIONS
$.post( - calls POST
Both are different. Postman calls "POST" properly, but when we call it, it will be "OPTIONS".
For C# web services - Web API
Please add the following code in your web.config file under the <system.webServer> tag. This will work:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
Please make sure you are not doing any mistake in the Ajax call.
jQuery
$.ajax({
url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST", /* or type:"GET" or type:"PUT" */
dataType: "json",
data: {
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
Note: If you are looking for downloading content from a third-party website then this will not help you. You can try the following code, but not JavaScript.
System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");
Deep
In the below investigation as API, I use http://example.com instead of http://myApiUrl/login from your question, because this first one working. I assume that your page is on http://my-site.local:8088.
NOTE: The API and your page have different domains!
The reason why you see different results is that Postman:
set header Host=example.com (your API)
NOT set header Origin
Postman actually not use your website url at all (you only type your API address into Postman) - he only send request to API, so he assume that website has same address as API (browser not assume this)
This is similar to browsers' way of sending requests when the site and API has the same domain (browsers also set the header item Referer=http://my-site.local:8088, however I don't see it in Postman). When Origin header is not set, usually servers allow such requests by default.
This is the standard way how Postman sends requests. But a browser sends requests differently when your site and API have different domains, and then CORS occurs and the browser automatically:
sets header Host=example.com (yours as API)
sets header Origin=http://my-site.local:8088 (your site)
(The header Referer has the same value as Origin). And now in Chrome's Console & Networks tab you will see:
When you have Host != Origin this is CORS, and when the server detects such a request, it usually blocks it by default.
Origin=null is set when you open HTML content from a local directory, and it sends a request. The same situation is when you send a request inside an <iframe>, like in the below snippet (but here the Host header is not set at all) - in general, everywhere the HTML specification says opaque origin, you can translate that to Origin=null. More information about this you can find here.
fetch('http://example.com/api', {method: 'POST'});
Look on chrome-console > network tab
If you do not use a simple CORS request, usually the browser automatically also sends an OPTIONS request before sending the main request - more information is here. The snippet below shows it:
fetch('http://example.com/api', {
method: 'POST',
headers: { 'Content-Type': 'application/json'}
});
Look in chrome-console -> network tab to 'api' request.
This is the OPTIONS request (the server does not allow sending a POST request)
You can change the configuration of your server to allow CORS requests.
Here is an example configuration which turns on CORS on nginx (nginx.conf file) - be very careful with setting always/"$http_origin" for nginx and "*" for Apache - this will unblock CORS from any domain (in production instead of stars use your concrete page adres which consume your api)
location ~ ^/index\.php(/|$) {
...
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
if ($request_method = OPTIONS) {
add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain charset=UTF-8';
return 204;
}
}
Here is an example configuration which turns on CORS on Apache (.htaccess file)
# ------------------------------------------------------------------------------
# | Cross-domain Ajax requests |
# ------------------------------------------------------------------------------
# Enable cross-origin Ajax requests.
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
# http://enable-cors.org/
# <IfModule mod_headers.c>
# Header set Access-Control-Allow-Origin "*"
# </IfModule>
# Header set Header set Access-Control-Allow-Origin "*"
# Header always set Access-Control-Allow-Credentials "true"
Access-Control-Allow-Origin "http://your-page.com:80"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
Applying a CORS restriction is a security feature defined by a server and implemented by a browser.
The browser looks at the CORS policy of the server and respects it.
However, the Postman tool does not bother about the CORS policy of the server.
That is why the CORS error appears in the browser, but not in Postman.
The error you get is due to the CORS standard, which sets some restrictions on how JavaScript can perform ajax requests.
The CORS standard is a client-side standard, implemented in the browser. So it is the browser which prevent the call from completing and generates the error message - not the server.
Postman does not implement the CORS restrictions, which is why you don't see the same error when making the same call from Postman.
Why doesn't Postman implement CORS? CORS defines the restrictions relative to the origin (URL domain) of the page which initiates the request. But in Postman the requests doesn't originate from a page with an URL so CORS does not apply.
Solution & Issue Origins
You are making a XMLHttpRequest to different domains, example:
Domain one: some-domain.com
Domain Two: some-different-domain.com
This difference in domain names triggers CORS (Cross-Origin Resource Sharing) policy called SOP (Same-Origin Policy) that enforces the use of same domains (hence Origin) in Ajax, XMLHttpRequest and other HTTP requests.
Why did it work when I made the request via the Chrome extension
Postman?
A client (most Browsers and Development Tools) has a choice to enforce the Same-Origin Policy.
Most browsers enforce the policy of Same-Origin Policy to prevent issues related to CSRF (Cross-Site Request Forgery) attack.
Postman as a development tool chooses not to enforce SOP while some browsers enforce, this is why you can send requests via Postman that you cannot send with XMLHttpRequest via JS using the browser.
For browser testing purposes:
Windows - Run:
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
The command above will disable chrome web security. So for example if you work on a local project and encounter CORS policy issue when trying to make a request, you can skip this type of error with the above command. Basically it will open a new chrome session.
You might also get this error if your gateway timeout is too short and the resource you are accessing takes longer to process than the timeout. This may be the case for complex database queries etc. Thus, the above error code can be disguishing this problem. Just check if the error code is 504 instead of 404 as in Kamil's answer or something else. If it is 504, then increasing the gateway timeout might fix the problem.
In my case the CORS error could be removed by disabling the same origin policy (CORS) in the Internet Explorer browser, see How to disable same origin policy Internet Explorer. After doing this, it was a pure 504 error in the log.
To resolve this issue, write this line of code in your doGet() or doPost() function whichever you are using in backend
response.setHeader("Access-Control-Allow-Origin", "*");
Instead of "*" you can type in the website or API URL endpoint which is accessing the website else it will be public.
Your IP address is not whitelisted, so you are getting this error.
Ask the backend staff to whitelist your IP address for the service you are accessing.
Access-Control-Allow-Headers
For me I got this issue for different reason, the remote domain was added to origins the deployed app works perfectly except one end point I got this issue:
Origin https://mai-frontend.vercel.app is not allowed by Access-Control-Allow-Origin. Status code: 500
and
Fetch API cannot load https://sciigo.herokuapp.com/recommendations/recommendationsByUser/8f1bb29e-8ce6-4df2-b138-ffe53650dbab due to access control checks.
I discovered that my Heroku database table does not contains all the columns of my local table after updating Heroku database table everything worked well.
It works for me by applying this middleware in globally:
<?php
namespace App\Http\Middleware;
use Closure;
class Cors {
public function handle($request, Closure $next) {
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', "Accept,authorization,Authorization, Content-Type");
}
}
Scenario
I am using fetch to gather json from my remote apache server. In the beginning I was receiving the following CORS violation:
Access to fetch at
'http://dev.mediajackagency.com/clients/dawna/row/wordpress/wp-content/uploads/2019/01/bw.jpg'
from origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
I overcame this issue by enabling CORS in the server's .htaccess file for this project
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
Now I'm getting a different CORS violation of
Access to fetch at
'http://some.domain/some/endpoint'
from origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: The
'Access-Control-Allow-Origin' header contains multiple values '*,
http://localhost:3000', but only one is allowed. Have the server send
the header with a valid value, or, if an opaque response serves your
needs, set the request's mode to 'no-cors' to fetch the resource with
CORS disabled.
Question
How can I find where the Access-Control-Allow-Origin is getting set for localhost:3000 ? I've done a full index and search for strings related to cors, headers, etc etc with no luck. All ideas are appreciated.
Extra
Via npm start the second ACAO value is localhost:3000 but via npm build the second ACAO value is localhost so the second value appears to be dynamic and restricted to React
Adding a proxy value to package.json doesn't appear to help at all
I ultimately could not decide if CRA's dev node server was creating this issue (by adding 'localhost:3000' as an allowed origin) or if I'm just not as good with .htaccess files as I thought. Regardless here is what finally ended up working:
API server's .htaccess
# allows image files to bypass cors #jkr
<Files *.jpg>
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
</Files>
#always allow preflight to pass #jkr
<LimitExcept OPTIONS>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
</LimitExcept>
I'm getting this error using ngResource to call a REST API on Amazon Web Services:
XMLHttpRequest cannot load
http://server.apiurl.com:8000/s/login?login=facebook. Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost' is therefore not allowed access.
Error 405
Service:
socialMarkt.factory('loginService', ['$resource', function ($resource) {
var apiAddress = "http://server.apiurl.com:8000/s/login/";
return $resource(apiAddress, {
login: "facebook",
access_token: "#access_token",
facebook_id: "#facebook_id"
}, {
getUser: {
method: 'POST'
}
});
}]);
Controller:
[...]
loginService.getUser(JSON.stringify(fbObj)),
function (data) {
console.log(data);
},
function (result) {
console.error('Error', result.status);
}
[...]
I'm using Chrome. What else can I do in order to fix this problem?
I've even configured the server to accept headers from origin localhost.
You are running into CORS issues.
There are several ways to fix or workaround this.
Turn off CORS. For example: How to turn off CORS in Chrome
Use a plugin for your browser
Use a proxy, such as nginx. Example of how to set up
Go through the necessary setup for your server. This is more a factor of the web server you have loaded on your EC2 instance (presuming this is what you mean by "Amazon web service"). For your specific server, you can refer to the enable CORS website.
More verbosely, you are trying to access api.serverurl.com from localhost. This is the exact definition of a cross-domain request.
By either turning it off just to get your work done (OK, but poor security for you if you visit other sites and just kicks the can down the road) or you can use a proxy which makes your browser think all requests come from the local host when really you have a local server that then calls the remote server.
So api.serverurl.com might become localhost:8000/api, and your local nginx or other proxy will send to the correct destination.
Now by popular demand, 100% more CORS information—the same great taste!
Bypassing CORS is exactly what is shown for those simply learning the front end.
HTTP Example with Promises
My "API Server" is a PHP application, so to solve this problem I found the below solution to work:
Place these lines in file index.php:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
In ASP.NET Core Web API, this issue got fixed by adding "Microsoft.AspNetCore.Cors" (ver 1.1.1) and adding the below changes in Startup.cs.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowAllHeaders",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
.
.
.
}
and
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Shows UseCors with named policy.
app.UseCors("AllowAllHeaders");
.
.
.
}
And putting [EnableCors("AllowAllHeaders")] in the controller.
There are some caveats when it comes to CORS. First, it does not allow wildcards *, but don't hold me on this one. I've read it somewhere, and I can't find the article now.
If you are making requests from a different domain, you need to add the allow origin headers.
Access-Control-Allow-Origin: www.other.com
If you are making requests that affect server resources like POST/PUT/PATCH, and if the MIME type is different than the following application/x-www-form-urlencoded, multipart/form-data, or text/plain the browser will automatically make a pre-flight OPTIONS request to check with the server if it would allow it.
So your API/server needs to handle these OPTIONS requests accordingly, you need to respond with the appropriate access control headers and the http response status code needs to be 200.
The headers should be something like this, adjust them for your needs:
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 86400
The max-age header is important, in my case, it wouldn't work without it, I guess the browser needs the info for how long the "access rights" are valid.
In addition, if you are making e.g. a POST request with application/json mime from a different domain you also need to add the previously mentioned allow origin header, so it would look like this:
Access-Control-Allow-Origin: www.other.com
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 86400
When the pre-flight succeeds and gets all the needed information your actual request will be made.
Generally speaking, whatever Access-Control headers are requested in the initial or pre-flight request, should be given in the response in order for it to work.
There is a good example in the MDN documentation here on this link, and you should also check out this Stack Overflow post.
If you're writing a Chrome extension
In the manifest.json file, you have to add the permissions for your domain(s).
"permissions": [
"http://example.com/*",
"https://example.com/*",
"http://www.example.com/*",
"https://www.example.com/*"
]
JavaScript XMLHttpRequest and Fetch follow the same-origin policy. So,
a web application using XMLHttpRequest or Fetch could only make HTTP
requests to its own domain.
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
You have to send the Access-Control-Allow-Origin: * HTTP header from your server side.
If you are using Apache as your HTTP server then you can add it to your Apache configuration file like this:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
Mod_headers is enabled by default in Apache, however, you may want to ensure it's enabled by running:
a2enmod headers
In PHP you can add the headers:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Expose-Headers: Content-Length, X-JSON");
header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: *");
...
To fix cross-origin-requests issues in a Node.js application:
npm i cors
And simply add the lines below to the app.js file:
let cors = require('cors')
app.use(cors())
If you are using the IIS server by chance, you can set the below headers in the HTTP request headers option.
Access-Control-Allow-Origin:*
Access-Control-Allow-Methods: 'HEAD, GET, POST, PUT, PATCH, DELETE'
Access-Control-Allow-Headers: 'Origin, Content-Type, X-Auth-Token';
With this all POST, GET, etc., will work fine.
In my Apache VirtualHost configuration file, I have added following lines:
Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
Our team occasionally sees this using Vue.js, Axios and a C# Web API. Adding a route attribute on the endpoint you're trying to hit fixes it for us.
[Route("ControllerName/Endpoint")]
[HttpOptions, HttpPost]
public IHttpActionResult Endpoint() { }
For a Python Flask server, you can use the flask-cors plugin to enable cross domain requests.
See: Flask-CORS
For anyone using API Gateway's HTTP API and the proxy route ANY /{proxy+}
You will need to explicitly define your route methods in order for CORS to work.
I wish this was more explicit in the AWS documentation for configuring CORS for an HTTP API
I was on a two-hour call with AWS support and they looped in one of their senior HTTP API developers, who made this recommendation.
For those who are using Lambda Integrated Proxy with API Gateway, you need configure your lambda function as if you are submitting your requests to it directly, meaning the function should set up the response headers properly. (If you are using custom lambda functions, this will be handled by the API Gateway.)
// In your lambda's index.handler():
exports.handler = (event, context, callback) => {
// On success:
callback(null, {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*"
}
}
}
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading of resources
From Cross-Origin Resource Sharing (CORS)
In short - the web server tells you (your browser) which sites you should trust for using that site.
Scammysite.bad tries to tell your browser to send a request to good-api-site.good
good-api-site.good tells your browser it should only trust other-good-site.good
Your browser says that you really should not trust scammysite.bad's request to good-api-site.good and goes CORS saved you.
If you are creating a site, and you really don't care who integrates with you. Plow on. Set * in your ACL.
However, if you are creating a site, and only site X, or even site X, Y and Z should be allowed, you use CORS to instruct the client's browser to only trust these sites to integrate with your site.
Browsers can of course choose to ignore this. Again, CORS protects your client - not you.
CORS allows * or one site defined. This can limit you, but you can get around this by adding some dynamic configuration to your web server - and help you being specific.
This is an example on how to configure CORS per site is in Apache:
# Save the entire "Origin" header in Apache environment variable "AccessControlAllowOrigin"
# Expand the regex to match your desired "good" sites / sites you trust
SetEnvIfNoCase Origin "^https://(other-good-site\.good|one-more-good.site)$" AccessControlAllowOrigin=$0
# Assuming you server multiple sites, ensure you apply only to this specific site
<If "%{HTTP_HOST} == 'good-api-site.com'">
# Remove headers to ensure that they are explicitly set
Header unset Access-Control-Allow-Origin env=AccessControlAllowOrigin
Header unset Access-Control-Allow-Methods env=AccessControlAllowOrigin
Header unset Access-Control-Allow-Headers env=AccessControlAllowOrigin
Header unset Access-Control-Expose-Headers env=AccessControlAllowOrigin
# Add headers "always" to ensure that they are explicitly set
# The value of the "Access-Control-Allow-Origin" header will be the contents saved in the "AccessControlAllowOrigin" environment variable
Header always set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
# Adapt the below to your use case
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, PUT" env=AccessControlAllowOrigin
Header always set Access-Control-Allow-Headers "X-Requested-With,Authorization" env=AccessControlAllowOrigin
Header always set Access-Control-Expose-Headers "X-Requested-With,Authorization" env=AccessControlAllowOrigin
</If>
I think disabling CORS from Chrome is not good way, because if you are using it in Ionic, certainly in a mobile build the issue will raise again.
So better to fix in your backend.
First of all, in the header, you need to set-
header('Access-Control-Allow-Origin: *');
header('Header set Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept"');
And if the API is behaving as both GET and POST, then also set in your header-
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') { if
(isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:
{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"); exit(0); }
A very common cause of this error could be that the host API had mapped the request to an HTTP method (e.g., PUT) and the API client is calling the API using a different http method (e.g., POST or GET).
Using the CORS option in the API gateway, I used the following settings shown above.
Also, note, that your function must return a HTTP status 200 in response to an OPTIONS request, or else CORS will also fail.
I am using AWS SDK for uploads, and after spending some time searching online, I stumbled upon this question. Thanks to #lsimoneau 45581857, it turns out the exact same thing was happening.
I simply pointed my request URL to the region on my bucket by attaching the region option and it worked.
const s3 = new AWS.S3({
accessKeyId: config.awsAccessKeyID,
secretAccessKey: config.awsSecretAccessKey,
region: 'eu-west-2' // add region here });
I have faced this problem when the DNS server was set to 8.8.8.8 (Google's). Actually, the problem was in the router. My application tried to connect with the server through Google, not locally (for my particular case).
I have removed 8.8.8.8 and this solved the issue. I know that this issues solved by CORS settings, but maybe someone will have the same trouble as me.
Check if request is going to correct endpoint. In my Node.js project, I mentioned incorrect endpoint, the request was going to /api/txn/12345, the endpoint was /api/txn instead of /api/txn/:txnId, that led to this error.
It's easy to solve this issue just with a few steps easily, without worrying about anything.
Kindly, follow the steps to solve it.
open (https://www.npmjs.com/package/cors#enabling-cors-pre-flight)
go to installation and copy the command npm install cors to install via Node.js in a terminal
go to Simple Usage (Enable All CORS Requests) by scrolling. Then copy and paste the complete declaration in your project and run it...that will work for sure...
copy the comment code and paste in your app.js or any other project and give a try...this will work. This will unlock every cross origin resource sharing...so we can switch between servers for your use
The stand-alone distributions of GeoServer include the Jetty application server. Enable cross-origin resource sharing (CORS) to allow JavaScript applications outside of your own domain to use GeoServer.
Uncomment the following <filter> and <filter-mapping> from webapps/geoserver/WEB-INF/web.xml:
<web-app>
<filter>
<filter-name>cross-origin</filter-name>
<filter-class>org.eclipse.jetty.servlets.CrossOriginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cross-origin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
The "Response to preflight request doesn't pass access control check" is exactly what the problem is:
Before issuing the actual GET request, the browser is checking if the service is correctly configured for CORS. This is done by checking if the service accepts the methods and headers going to be used by the actual request. Therefore, it is not enough to allow the service to be accessed from a different origin, but also the additional requisites must be fulfilled.
Setting headers to
Header always set Access-Control-Allow-Origin: www.example.com
Header always set Access-Control-Allow-Methods: GET, POST, PUT, PATCH, POST, DELETE, OPTIONS
Header always set Access-Control-Allow-Headers: Content-Type #etc...
will not suffice. You have to add a rewrite rule:
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
A great read Response for preflight does not have HTTP ok status.
I made it work, adding the OPTIONS method to Access-Control-Allow-Methods:
Access-Control-Allow-Methods: GET, OPTIONS
But!, again, this works in Chrome and Firefox, but sadly not in Chromium.
Something that is very easy to miss...
In Solution Explorer, right-click api-project. In the properties window, set 'Anonymous Authentication' to Enabled!!!
Disable the Chrome security.
Create a Chrome shortcut: right click → Properties → Target. Paste this: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chromedev"
Dreamhost support wasn't able to help me much on this, and I've done a lot of googling but to no avail. My client's site has been down for at least 12 hours and I need help getting it back up. There are two levels to this problem because my development server is having a similar, but slightly different issue.
My setup is that I have Drupal 8 running at a subdomain and a ReactJS app being served from the main domain. I have the JSON:API module installed and I'm using the fetch api in React to get data from Drupal. No authentication or other Methods, just getting data for my app to use. Everything worked yesterday and I hadn't changed anything on hosting or deployed any new code.
The initial error I was getting in the browser javascript console was this:
Access to fetch at 'http://CMS_URL/jsonapi/node/person_page' from origin 'http://SITE_URL' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Dreamhost support suggested that I add the following code to my .htaccess file:
Header add Access-Control-Allow-Origin: "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header add Access-Control-Allow-Headers: "Content-Type"
This is my services.yml file located at /sites/default:
parameters:
cors.config:
enabled: true
# Specify allowed headers, like 'x-allowed-header'.
allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with', '*']
# Specify allowed request methods, specify ['*'] to allow all possible ones.
allowedMethods: ['GET']
# Configure requests allowed from specific origins.
allowedOrigins: ['*']
# Sets the Access-Control-Expose-Headers header.
exposedHeaders: true
# Sets the Access-Control-Max-Age header.
maxAge: 1000
# Sets the Access-Control-Allow-Credentials header.
supportsCredentials: false
When I visit the domain I just get a 403 (Forbidden) error, but on my development server (nodejs) I get the following errors:
Access to fetch at 'http://CMS_URL/jsonapi/node/slide_page/fe770c69-8d4d-489f-9ab9-8e6abce55bb4' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:3000, *', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
AND
Cross-Origin Read Blocking (CORB) blocked cross-origin response http://CMS_URL/jsonapi/node/slide_page/fe770c69-8d4d-489f-9ab9-8e6abce55bb4 with MIME type application/vnd.api+json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
I suspect that there is some issue with these two files not playing well together, but I can't figure out what is causing the problems. I've tried variations on the settings for Access-Control-Allow-Origin and allowedOrigins on .htaccess and services.yml respectively and nothing seems to be changing anything.
Can anyone point me in the right direction?
edited to remove exact urls
After some work with Dreamhost support and some playing around we figured out a solution to this. For this particular configuration, CORS policy has to be correctly configured for the hosting AND Drupal. These are the settings that ended up working for us:
Added the following to the .htaccess file under the domain root of the CMS:
# enable CORS
Header add Access-Control-Allow-Origin: "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Header add Access-Control-Allow-Headers: "Content-Type"
Under the /sites/default directory, added a settings.yml file with the following content:
parameters:
cors.config:
enabled: false
# Specify allowed headers, like 'x-allowed-header'.
allowedHeaders: ['x-csrf-token','authorization','content-type','accept','origin','x-requested-with', '*']
# Specify allowed request methods, specify ['*'] to allow all possible ones.
allowedMethods: ['*']
# Configure requests allowed from specific origins.
allowedOrigins: ['*']
# Sets the Access-Control-Expose-Headers header.
exposedHeaders: true
# Sets the Access-Control-Max-Age header.
maxAge: 1000
# Sets the Access-Control-Allow-Credentials header.
supportsCredentials: false
The key thing that was tripping us up was how the file changes could be made to be effective. Changes to the .htaccess file were immediately effective, but changes to the settings.yml file required that we clear the cache in Drupal:
Configuration->Development->Performace->Clear cache