对飞行前请求的响应没有通过访问控制检查

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.

转载于:https://stackoverflow.com/questions/35588699/response-to-preflight-request-doesnt-pass-access-control-check

csdnceshi55
~Onlooker with Node JS this stackoverflow.com/a/40026625/7822663 link helped me to solve the issue
大约 3 年之前 回复
csdnceshi68
local-host But turning off security is just an ugly workaround where you are compromising on security,doesnt solve your problem...
3 年多之前 回复
csdnceshi79
python小菜 Thx for the comments, it worked when I set the browser to turn of security
4 年多之前 回复
csdnceshi58
Didn"t forge 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
4 年多之前 回复
csdnceshi77
狐狸.fox 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.
4 年多之前 回复
csdnceshi58
Didn"t forge You clearly haven't done enough to enable CORS on server side. Post sample of response headers
4 年多之前 回复
csdnceshi62
csdnceshi62 confused: did you "configure the server" or is this "a rest api on amazon web service"?
4 年多之前 回复

19个回答

You are running into CORS issues.

There are several ways to fix 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

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, put poor security for you if you visit other sites and just kicks the can down the road) 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!


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

csdnceshi66
必承其重 | 欲带皇冠 You have saved my 3 days work, was really getting frustrated, Thanks for post
大约 2 年之前 回复
csdnceshi64
游.程 Thank 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/…
大约 2 年之前 回复
csdnceshi72
谁还没个明天 You can check here for your server type. w3.org/wiki/CORS_Enabled
2 年多之前 回复
csdnceshi80
胖鸭 how yo set it up in the right way
2 年多之前 回复
weixin_41568110
七度&光 I added chrome plugin and it worked for some days. Now it's not working.
接近 3 年之前 回复
weixin_41568126
乱世@小熊 How?
大约 4 年之前 回复
weixin_41568196
撒拉嘿哟木头 It actually worked. I added the flag to disable the Web security. For development is fine.
4 年多之前 回复
csdnceshi72
谁还没个明天 It is easy to down vote. Less easy to take the risk yourself my friend. And all of these work exactly in a dev environment.
4 年多之前 回复
csdnceshi63
elliott.david left out the obvious one of implementing CORS correctly
4 年多之前 回复

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');
csdnceshi51
旧行李 and whatthefish put before any output
大约 2 年之前 回复
csdnceshi62
csdnceshi62 Where to put it in an Angular 6 project?
2 年多之前 回复
csdnceshi66
必承其重 | 欲带皇冠 Where do you put this though? On the root get endpoint?
2 年多之前 回复
weixin_41568184
叼花硬汉 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.
2 年多之前 回复

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.

csdnceshi65
larry*wei 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");
大约 2 年之前 回复
csdnceshi77
狐狸.fox 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.
3 年多之前 回复

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

weixin_41568174
from.. Good answer! I wonder no upvotes for it.
接近 2 年之前 回复

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>
csdnceshi70
笑故挽风 not using GeoServer, but this clip helped me to know the settings i should use on the app receiving the call.
2 年多之前 回复
csdnceshi69
YaoRaoLov That did not add antyhing to response header, so it did not worked
2 年多之前 回复

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" : "*"
           }
     }
}
csdnceshi78
程序go 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.
大约 2 年之前 回复

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

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

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

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/*"
]
csdnceshi75
衫裤跑路 saved my bacon!
2 年多之前 回复
weixin_41568174
from.. Also check if you have www prefix
2 年多之前 回复

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.

共19条数据 1 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问