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


当前回答

对于Python Flask服务器,您可以使用Flask -cors插件来启用跨域请求。

看:Flask-CORS

其他回答

有些东西很容易被忽略……

在解决方案资源管理器中,右键单击api-project。在属性窗口中,将“匿名身份验证”设置为启用!!

在PHP中,你可以添加头文件:

<?php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Expose-Headers: Content-Length, X-JSON");
    header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: *");
    ...

当DNS服务器设置为8.8.8.8(谷歌’s)时,我遇到过这个问题。事实上,问题出在路由器上。我的应用程序试图通过谷歌连接服务器,而不是本地连接(对于我的特定情况)。

我已经删除了8.8.8.8,这解决了这个问题。我知道CORS设置解决了这个问题,但是可能有人会遇到和我一样的问题。

我们的团队在使用Vue.js、Axios和c# Web API时偶尔会遇到这种情况。在您试图命中的端点上添加路由属性为我们修复了它。

[Route("ControllerName/Endpoint")]
[HttpOptions, HttpPost]
public IHttpActionResult Endpoint() { }

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

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

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