Response to preflight request doesn't pass access control check
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
You are running into CORS issues.
There are several ways to fix this.
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.
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');
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.
上一篇: 如何动态加载JavaScript文件?
下一篇: 对预检请求的响应不会通过访问控制检查