Response to preflight request doesn't pass access control check

JavascriptAjaxHttpCorsHttp Status-Code-405

Javascript Problem Overview


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, and I dont know what else to do in order to fix this problem. I've even configured the server to accept headers from origin localhost.

Javascript Solutions


Solution 1 - Javascript

You are running into CORS issues.

There are several ways to fix/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 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 local host when really you have 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 info][4]....same great taste!


Bypassing CORS is exactly what is shown for those simply learning the front end. https://codecraft.tv/courses/angular/http/http-with-promises/

[4]: https://www.w3.org/wiki/CORS_Enabled "!00% more CORS info"

Solution 2 - Javascript

My "API Server" is an PHP Application so to solve this problem I found the below solution to work:

Place the lines in 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');

Solution 3 - Javascript

In AspNetCore web api, this issue got fixed by adding "Microsoft.AspNetCore.Cors" (ver 1.1.1) and adding the below changes on 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")] on the controller.

Solution 4 - Javascript

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 info 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 docs here on this link, and you should also check out this SO post

Solution 5 - Javascript

If you're writing a chrome-extension

You have to add in the manifest.json the permissions for your domain(s).

"permissions": [
   "http://example.com/*",
   "https://example.com/*",
   "http://www.example.com/*",
   "https://www.example.com/*"
]

Solution 6 - Javascript

> 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

Solution 7 - Javascript

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

Solution 8 - Javascript

To fix cross-origin-requests issues in a Node JS application:

npm i cors

And simply add the lines below to the app.js

let cors = require('cors')
app.use(cors())

Solution 9 - Javascript

If you are using IIS server by chance. you can set 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.

Solution 10 - Javascript

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

See : https://flask-cors.readthedocs.io/en/latest/

Solution 11 - Javascript

Our team occasionally sees this using Vue, axios and a C# WebApi. Adding a route attribute on the endpoint you're trying to hit fixes it for us.

[Route("ControllerName/Endpoint")]
[HttpOptions, HttpPost]
public IHttpActionResult Endpoint() { }

Solution 12 - Javascript

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

Wish this was more explicit in the AWS Docs for Configuring CORS for an HTTP API

Was on a 2 hour call with AWS Support and they looped in one of their senior HTTP API developers, who made this recommendation.

Hopefully this post can save some time and effort for those who are working with Api Gateway HTTP API.

Solution 13 - Javascript

In my Apache VirtualHost config 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]

Solution 14 - Javascript

For those 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" : "*"
           }
     }
}

Solution 15 - Javascript

I think disabling CORS from Chrome is not good way, because if you are using it in ionic, certainly in Mobile Build the Issue will raise Again.

So better to Fix in your Backend.

First of all In 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 API is behaving as GET and POST both 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); }

Solution 16 - Javascript

A very common cause of this error could be that the host API had mapped the request to a http method (e.g. PUT) and the API client is calling the API using a different http method (e.g. POST or GET)

Solution 17 - Javascript

> 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

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

In short - the webserver 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 clients 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 pr 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>

Solution 18 - Javascript

I have faced with this problem when DNS server was set to 8.8.8.8 (google's). Actually, the problem was in router, my application tried to connect with server through the 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

Solution 19 - Javascript

I am using AWS sdk for uploads, after spending some time searching online i stumbled upon this thread. 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 });

Solution 20 - Javascript

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.

Solution 21 - Javascript

The standalone 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>

Solution 22 - Javascript

It's easy to solve this issue just with 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 terminal
  3. go to Simple Usage (Enable All CORS Requests) by scrolling.then copy and paste the complete declartion in ur project and run it...that will work for sure.. copy the comment code and paste in ur 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 serves for your use

Solution 23 - Javascript

Something that is very easy to miss...

IN solution explorer, right-click api-project. In properties window set 'Anonymous Authentication' to Enabled !!!

Solution 24 - Javascript

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndre MendesView Question on Stackoverflow
Solution 1 - JavascriptE. MagginiView Answer on Stackoverflow
Solution 2 - JavascriptSlipstreamView Answer on Stackoverflow
Solution 3 - JavascriptRajkumar PeterView Answer on Stackoverflow
Solution 4 - JavascriptSasa BlagojevicView Answer on Stackoverflow
Solution 5 - JavascriptfreedevView Answer on Stackoverflow
Solution 6 - JavascriptTadejView Answer on Stackoverflow
Solution 7 - JavascriptatiruzView Answer on Stackoverflow
Solution 8 - JavascriptRohit ParteView Answer on Stackoverflow
Solution 9 - JavascriptSunil KumarView Answer on Stackoverflow
Solution 10 - JavascriptTeriblusView Answer on Stackoverflow
Solution 11 - Javascriptw00ngyView Answer on Stackoverflow
Solution 12 - JavascriptTrieuNomadView Answer on Stackoverflow
Solution 13 - JavascripthugsbrugsView Answer on Stackoverflow
Solution 14 - JavascriptXu ChenView Answer on Stackoverflow
Solution 15 - JavascriptShubham PandeyView Answer on Stackoverflow
Solution 16 - JavascriptChristian OliverView Answer on Stackoverflow
Solution 17 - JavascriptsastorslView Answer on Stackoverflow
Solution 18 - JavascriptKirill HusiatynView Answer on Stackoverflow
Solution 19 - JavascriptdavyCodeView Answer on Stackoverflow
Solution 20 - JavascriptFiach ReidView Answer on Stackoverflow
Solution 21 - JavascriptYassine Ech-CharafiView Answer on Stackoverflow
Solution 22 - JavascriptRahul sahView Answer on Stackoverflow
Solution 23 - JavascriptWesView Answer on Stackoverflow
Solution 24 - JavascriptNithinView Answer on Stackoverflow