我使用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的头文件。


当前回答

JavaScript XMLHttpRequest和Fetch遵循同源策略。所以, 使用XMLHttpRequest或Fetch的web应用程序只能生成HTTP 请求到自己的域。

来源:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

你必须从你的服务器端发送Access-Control-Allow-Origin: * HTTP报头。

如果你使用Apache作为你的HTTP服务器,那么你可以像这样把它添加到你的Apache配置文件中:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Mod_headers在Apache中默认是启用的,但是,你可能想通过运行以下命令来确保它是启用的:

 a2enmod headers

其他回答

我的“API服务器”是一个PHP应用程序,所以为了解决这个问题,我发现下面的解决方案可以工作:

将这些行放入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');

如果您碰巧使用IIS服务器,您可以在HTTP请求头选项中设置以下头。

Access-Control-Allow-Origin:*
Access-Control-Allow-Methods: 'HEAD, GET, POST, PUT, PATCH, DELETE'
Access-Control-Allow-Headers: 'Origin, Content-Type, X-Auth-Token';

所有这些POST、GET等都可以正常工作。

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

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

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

我正在使用AWS SDK进行上传,在花了一些时间在网上搜索之后,我偶然发现了这个问题。多亏了@lsimoneau 45581857,原来发生了完全相同的事情。

我只是通过附加区域选项将请求URL指向bucket上的区域,它就工作了。

 const s3 = new AWS.S3({
 accessKeyId: config.awsAccessKeyID,
 secretAccessKey: config.awsSecretAccessKey,
 region: 'eu-west-2'  // add region here });

要修复Node.js应用程序中的跨源请求问题:

npm i cors

然后简单地将下面的代码添加到app.js文件中:

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