732

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.

8
  • 1
    confused: did you "configure the server" or is this "a rest api on amazon web service"?
    – dandavis
    Commented Feb 23, 2016 at 21:42
  • 3
    You clearly haven't done enough to enable CORS on server side. Post sample of response headers
    – charlietfl
    Commented Feb 23, 2016 at 21:44
  • 4
    Either way your down votes are wrong. He is hosting his files on his local machine. It won't matter what kind of conf he does on the back end. Angular will not allow this pre flight.
    – user796446
    Commented Feb 23, 2016 at 21:53
  • 3
    Thx for the comments, it worked when I set the browser to turn of security Commented Feb 24, 2016 at 0:12
  • 4
    @Andre But turning off security is just an ugly workaround where you are compromising on security,doesnt solve your problem...
    – shivi
    Commented Apr 6, 2017 at 6:50

27 Answers 27

340

You are running into CORS issues.

There are several ways to fix or workaround this.

  1. Turn off CORS. For example: How to turn off CORS in Chrome
  2. Use a plugin for your browser
  3. Use a proxy, such as nginx. Example of how to set up
  4. 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

10
  • @Xvegas You can check here for your server type. w3.org/wiki/CORS_Enabled
    – user796446
    Commented Jul 3, 2018 at 15:26
  • 145
    Disabling cors in browser? This is not a solution, it's an workaround that doesnt help who really need CORS enabled. Commented Dec 4, 2018 at 17:08
  • 5
    @JonathanSimas As stated, it is one of several ways to continue with development work. Work-arounds ARE solutions. You'll even note in my answer I say this is poor security and really just kicks the can down the road. ;-)
    – user796446
    Commented Dec 4, 2018 at 21:37
  • 2
    you should at least mention that there's a solution which is proper in many cases which is setting CORS. If you do, there will be less to no downvotes anymore
    – YakovL
    Commented Sep 19, 2019 at 11:03
  • 6
    Turn off cors in chrome or plugin in chrome has NEVER a real solution (if website have CORS problem, you will ask EACH client to disable their CORS before ? ). Thanks for the response but I would prefer that you mark these two points as fake solution. The real solution is to configure the WS/API to allow allowed origine
    – Mahefa
    Commented Oct 20, 2021 at 18:21
235

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');
10
  • 14
    I agree, this is better than the accepted answer although be careful when copying these lines, make sure to modify the methods and the origin. Commented Apr 15, 2018 at 10:39
  • @CodyBugstein and whatthefish put before any output Commented Jul 30, 2018 at 23:10
  • My client app stopped working when I added a header that is only required by some servers. If the request includes any custom headers, they will need to be listed in Access-Control-Allow-Headers.
    – z0r
    Commented Jul 16, 2019 at 6:25
  • @Slipstream So would this be done in the receiving server or the server that has the file that sends the post request?
    – user14983900
    Commented Mar 24, 2021 at 14:37
  • @AlphaMirage On the receiving server
    – Slipstream
    Commented Mar 24, 2021 at 14:45
64

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.

2
  • 34
    This is a fine answer if you want to build in cross site scripting vulnerabilities! Please do not ever do this! Specify your domains that you can access to avoid security problems. CORS is there for a reason.
    – crthompson
    Commented Jun 20, 2017 at 21:29
  • 3
    Just to make it clearer @paqogomez, in your ConfigureServices method: services.AddCors(options => { options.AddPolicy("AllowSpecificOrigin", builder => { builder.WithOrigins("localhost") .AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod(); }); }); and in your Configure method: app.UseCors("AllowSpecificOrigin");
    – Tena
    Commented Oct 8, 2018 at 10:10
49

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.

3
  • 1
    Here is the Mozilla article talking about how you can't use wildcard for cors origin: Link So apparently this only applies when using credentials (if I'm understanding correctly) Commented Jun 21, 2019 at 17:56
  • I'm using wildcard and submitting a bearer token to authorize the request and it's working fine so not sure what the link I provided above is referring to regarding credentials. My issue was that when bulding my CORS policy in .Net Core I didn't add .AllowCredentials(). After adding .AllowCredentials() everything worked. Commented Jun 24, 2019 at 16:06
  • Access-Control-Allow-Origin: www.other.com has no chance of ever working, since www.other.com is not a valid origin value.
    – jub0bs
    Commented May 1, 2023 at 9:41
19

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/*"
]
1
  • 3
    Also check if you have www prefix Commented May 6, 2018 at 9:45
16

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
4
  • Where can I find my Apache configuration file? Commented May 31, 2018 at 7:42
  • @ShubhamArya on linux Debian the default location is: /etc/apache2/apache2.conf
    – ttt
    Commented May 31, 2018 at 11:09
  • where can I find it in windows? Commented Jun 2, 2018 at 8:08
  • 2
    @Shubham Arya : windows default location is C:\Program Files\Apache\Apache2\conf\httpd.conf , you can find more details in httpd.apache.org/docs/2.0/platform/windows.xml
    – Kube Kubow
    Commented Aug 27, 2020 at 5:51
12

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: *");
    ...
0
10

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())
2
  • 6
    this only works in express js apps, not all node apps
    – DrCord
    Commented Jun 3, 2019 at 16:03
  • Running locally, these lines are not outputting the Access-Control-Allow-Origin header in my Node JS express app.
    – EGP
    Commented Feb 15, 2023 at 3:34
10

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.

1
  • Note that listing Origin in the Access-Control-Allow-Headers header is never required.
    – jub0bs
    Commented May 1, 2023 at 9:42
9

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]
3
  • It works for me when I keep this code in .htaccess file in cPanel hosting server Commented Aug 14, 2022 at 4:52
  • Note that listing Origin in the Access-Control-Allow-Headers header is never required.
    – jub0bs
    Commented May 1, 2023 at 9:42
  • OMG HOURS OF SEARCHING AND THE RewriteEngine rules is all I needed :)
    – Jwags
    Commented Sep 6 at 13:50
7

For a Python Flask server, you can use the flask-cors plugin to enable cross domain requests.

See: Flask-CORS

5

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() { }
2
  • What is that code in? C#? Java? Commented Sep 18, 2022 at 0:06
  • Apologies for the delay @PeterMortensen - This is in C#.
    – w00ngy
    Commented Dec 9, 2022 at 15:50
4

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.

Enter image description here

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.

0
4

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" : "*"
        }
    }
}
1
  • 1
    I want to also chime in and mention one big gotcha I dont think AWS documents. Say you use API gateway to proxy your lambda function, and you use some API in that lambda function. If that API returns a non-200 success success code and you didn't add the non-200 success code into the method response in API gateway then you will receive an error and not see your successful response. Examples for this: Sendgrid and Twilio have non-200 success codes. Commented Aug 1, 2018 at 20:29
3

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.

  1. Scammysite.bad tries to tell your browser to send a request to good-api-site.good
  2. good-api-site.good tells your browser it should only trust other-good-site.good
  3. 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>
0
3

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); }

2

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).

0
1

Enter image description here

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.

1

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 });
1

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.

1

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.

1

If some poor soul like me is out there using Django and Nginx with Swagger UI and you've been stuck trying to get an endpoint working with Docker and local https--- make sure you've set your Swagger config to use: 'https://<local-domain.local>'

0

It's easy to solve this issue just with a few steps easily, without worrying about anything.

Kindly, follow the steps to solve it.

  1. open (https://www.npmjs.com/package/cors#enabling-cors-pre-flight)
  2. go to installation and copy the command npm install cors to install via Node.js in a terminal
  3. 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
2
  • 1
    var express = require('express') var cors = require('cors') var app = express() app.use(cors()) app.get('/products/:id', function (req, res, next) { res.json({msg: 'This is CORS-enabled for all origins!'}) }) app.listen(80, function () { console.log('CORS-enabled web server listening on port 80') })
    – Rahul sah
    Commented Nov 10, 2019 at 19:38
  • In my opinion this is also only valid in express node apps but not any others.
    – Kube Kubow
    Commented Aug 27, 2020 at 5:42
0

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>
1
  • That did not add antyhing to response header, so it did not worked
    – JollyRoger
    Commented Apr 22, 2018 at 4:14
0

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.

0

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.

6
  • Listing OPTIONS in the Access-Control-Allow-Methods header is only useful if clients are explicitly sending requests that use OPTIONS as method (e.g. with fetch(url, {method: 'OPTIONS'}). In general, listing OPTIONS in the Access-Control-Allow-Methods header is not necessary for preflight to succeed.
    – jub0bs
    Commented May 1, 2023 at 9:44
  • No, prelight request is essentially using OPTIONS @jub0bs
    – Stan
    Commented May 26, 2023 at 16:19
  • @Stan That preflight requests use OPTIONS as a method doesn't mean you necessarily need to allow OPTIONS in your CORS configuration. This CORS playground (in which OPTIONS is not listed) may be enough to convince you; if not, check out the Fetch standard.
    – jub0bs
    Commented May 26, 2023 at 18:33
  • @jub0bs well if it is within the same domain, I guess it is not. Otherwise I guesss brower will send the options on your behalf
    – Stan
    Commented May 28, 2023 at 1:02
  • @jub0bs plus I am able to see it has sent a prelight request using option first: prnt.sc/4TdbzmyZhHrX that is what I mean.
    – Stan
    Commented May 28, 2023 at 1:07
-1

Something that is very easy to miss...

In Solution Explorer, right-click api-project. In the properties window, set 'Anonymous Authentication' to Enabled!!!

1
  • This presumably refer to something in Visual Studio. Related to IIS and ASP.NET? We will probably never know (the OP has left the building - "Last seen more than 3 years ago") Commented Sep 18, 2022 at 0:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.