我使用ngResource在亚马逊Web服务上调用REST API得到这个错误:

XMLHttpRequest无法加载 http://server.apiurl.com: 8000 / s /登录吗? =登录facebook。应对 飞行前请求未通过门禁检查:否 'Access-Control-Allow-Origin'头出现在被请求的对象上 资源。因此,来源“http://localhost”不允许访问。 错误405

服务:

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

控制器:

[...]
loginService.getUser(JSON.stringify(fbObj)),
    function (data) {
        console.log(data);
    },
    function (result) {
        console.error('Error', result.status);
    }
[...]

我用Chrome浏览器。为了解决这个问题,我还能做些什么?

我甚至将服务器配置为接受来自源localhost的头文件。


当前回答

检查请求是否发送到正确的端点。在我的Node.js项目中,我提到了错误的端点,请求将前往/api/txn/12345,端点是/api/txn而不是/api/txn/:txnId,这导致了这个错误。

其他回答

解决这个问题很简单,只需要几个步骤,不用担心任何事情。

请遵循以下步骤来解决它。

open (https://www.npmjs.com/package/cors#enabling-cors-pre-flight) go to installation and copy the command npm install cors to install via Node.js in a terminal 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

检查请求是否发送到正确的端点。在我的Node.js项目中,我提到了错误的端点,请求将前往/api/txn/12345,端点是/api/txn而不是/api/txn/:txnId,这导致了这个错误。

在ASP。NET Core Web API,这个问题通过添加“Microsoft.AspNetCore. NET”得到了解决。Cors”(版本1.1.1),并在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");
    .
    .
    .
}

并在控制器中放入[EnableCors("AllowAllHeaders")]。

使用API网关中的CORS选项,我使用了上面所示的以下设置。

另外,请注意,函数必须返回HTTP状态200以响应OPTIONS请求,否则CORS也会失败。

你遇到了CORS问题。

有几种方法可以修复或解决这个问题。

关闭CORS。例如:如何在Chrome中关闭CORS 为你的浏览器使用插件 使用代理,例如nginx。示例如何设置 完成服务器的必要设置。这与您在EC2实例上加载的web服务器有关(假设这就是您所说的“Amazon web服务”)。对于特定的服务器,可以参考启用CORS网站。

更详细地说,您试图从localhost访问api.serverurl.com。这就是跨域请求的确切定义。

通过关闭它来完成你的工作(好吧,但是如果你访问其他网站,你的安全性就差了),或者你可以使用代理,让你的浏览器认为所有的请求都来自本地主机,而实际上你有一个本地服务器,然后调用远程服务器。

所以api.serverurl.com可能变成localhost:8000/api,你的本地nginx或其他代理将发送到正确的目的地。


现在,根据大众的需求,更多的CORS信息-同样的美味!


绕过CORS正是为那些只是学习前端的人所展示的。 带有承诺的HTTP示例