Response to preflight request doesn't pass access control check
Solution 1
You are running into CORS issues.
There are several ways to fix/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 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....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/
Solution 2
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
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
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
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/*"
]

Andre Mendes
Updated on July 08, 2022Comments
-
Andre Mendes 6 months
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
.-
dandavis almost 7 yearsconfused: did you "configure the server" or is this "a rest api on amazon web service"?
-
charlietfl almost 7 yearsYou clearly haven't done enough to enable CORS on server side. Post sample of response headers
-
E. Maggini almost 7 yearsEither 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.
-
charlietfl almost 7 years@E.Maggini browser doesn't care where server is.... it only knows to make a request...as long as request contains proper headers browser could care less where they come from. Issue has absolutely nothing to do with angular. It's the browser itself that makes the OPTIONS request
-
Andre Mendes almost 7 yearsThx for the comments, it worked when I set the browser to turn of security
-
shivi over 5 years@Andre But turning off security is just an ugly workaround where you are compromising on security,doesnt solve your problem...
-
Poorna over 5 yearswith Node JS this stackoverflow.com/a/40026625/7822663 link helped me to solve the issue
-
Ramesh Roddam about 4 yearsPlease refer to this post for answer nd how to solve this problem stackoverflow.com/questions/53528643/…
-
-
crthompson over 5 yearsThis 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.
-
Marcel almost 5 yearsI added chrome plugin and it worked for some days. Now it's not working.
-
Amir Savand over 4 yearsI agree, this is better than the accepted answer although be careful when copying these lines, make sure to modify the methods and the origin.
-
JollyRoger over 4 yearsThat did not add antyhing to response header, so it did not worked
-
Matt Felzani over 4 yearsnot using GeoServer, but this clip helped me to know the settings i should use on the app receiving the call.
-
Vlas Bashynskyi over 4 yearsAlso check if you have www prefix
-
Shubham Arya over 4 yearsWhere can I find my Apache configuration file?
-
Tadej over 4 years@ShubhamArya on linux Debian the default location is:
/etc/apache2/apache2.conf
-
Shubham Arya over 4 yearswhere can I find it in windows?
-
E. Maggini over 4 years@Xvegas You can check here for your server type. w3.org/wiki/CORS_Enabled
-
whatthefish over 4 yearsWhere to put it in an Angular 6 project?
-
That Realty Programmer Guy over 4 years@CodyBugstein and whatthefish put before any output
-
Stephen Tetreault over 4 yearsI 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.
-
Always_a_learner over 4 yearsThank you you saved my day. Used first option only: C:\Program Files (x86)\Google\Chrome\Application>chrome.exe --user-data-dir="C:\Chrome dev session" --disable-web-security. From: stackoverflow.com/questions/3102819/…
-
fguillen about 4 yearsI was implementing CORS properly in my server but I forgot to add the
PUT
method -
Tena about 4 yearsJust 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");
-
Jose Seie about 4 yearsthanks, it worked for me! in tests and production environment. Even using https://
-
Jonathan Simas about 4 yearsDisabling cors in browser? This is not a solution, it's an workaround that doesnt help who really need CORS enabled.
-
E. Maggini about 4 years@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. ;-)
-
w00ngy almost 4 yearsWe aren't really sure why. Lol. If anyone does let me know!
-
Ashfaque Rifaye almost 4 yearsHow do we set up the server communication in a dev server/prod server? Please explain ..
-
Silambarasan R.D almost 4 years@atiruz Thanks for the solution. This Works When I added the line
header ("Access-Control-Expose-Headers: Content-Length, X-JSON");
-
Romeo Sierra over 3 years@AshfaqueRifaye That's a separate question you are asking with a very broad answer...
-
DrCord over 3 yearsthis only works in express js apps, not all node apps
-
Post Impatica over 3 yearsHere 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)
-
Post Impatica over 3 yearsI'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. -
z0r over 3 yearsMy 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
. -
YakovL over 3 yearsyou 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 over 3 years@E.Maggini yeah, but with more meanigful label, I wouldn't guess that "100% more CORS info" is actually about setting CORS on server. I can't suggest edits since I have more than 2K reputation, but if you like, I can edit the post and you may rollback/edit if you don't like some bits. What do you think?
-
Rahul sah about 3 yearsvar 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') })
-
Bon over 2 years@whatthefish this is a server side change, not a client side change.
-
iprashant over 2 yearsany solution for non Express js apps ?
-
Kube Kubow over 2 yearsIn my opinion this is also only valid in express node apps but not any others.
-
Kube Kubow over 2 years@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 -
amirlol almost 2 yearsThis was exactly my issue. Thank you!
-
Asma Rahim Ali Jafri almost 2 yearsCan someone help as to where to put this in a react app?
-
Slipstream almost 2 years@AsmaRahimAliJafri this has to be done on the Server-side!
-
puk almost 2 yearsThis was a life saver as there is very limited documentation on extensions/plugins
-
Admin over 1 year@Slipstream So would this be done in the receiving server or the server that has the file that sends the post request?
-
Slipstream over 1 year@AlphaMirage On the receiving server
-
Admin over 1 year@Slipstream I did that... It still doesn't work! I am using node.js and express.js. Should I show my code? We can have a chat room? Thanks!
-
Slipstream over 1 yearSorry @AlphaMirage, node.js is not my specialty :) The important point is that this issue happens on the server-side, not on the client-side.
-
Admin over 1 year@Slipstream Yep, I understand! It is fine! I was able to make it work! We all have our strenghts!
-
AntiCZ over 1 year@iprashant Look what cors lib is doing and do the same.
-
Mohamed Iqzas over 1 year@AntiCZ no need to look at cors.. look at express how it is using cors as a middleware.. route all your requests through cors api... and then to your actual api...
-
Mahefa about 1 yearTurn 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
-
E. Maggini about 1 year@Mahefa I refer you to the final link in the answer. There are times when turning off CORS is perfectly valid for development purposes. codecraft.tv/courses/angular/http/http-with-promises