【问题标题】:Angular JS Cors No 'Access-Control-Allow-Origin' header is present on the requested resource ErrorAngular JS Cors 请求的资源上不存在“Access-Control-Allow-Origin”标头错误
【发布时间】:2016-03-20 06:47:12
【问题描述】:

在我的 C# web api 上,我启用了 cors,即

[EnableCors(origins: "*", headers: "*", methods: "*")]

然后在我的 Angular js 网站中,我这样调用 post API

authService.login = function (credentials) {
                return $http
                    .post(WEB_CONFIG.login, credentials)
                    .then(function (res) {
                        Session.create(res.data.Email, res.data.Roles,res.data.Username);
                        return res.data.user;
                    });
            };

Angular 站点从 localhost:9000 发出请求,API 位于 localhost

得到错误

XMLHttpRequest 无法加载 http://localhost/mysite/api/user/login。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:9000' 因此不允许访问。

为什么我在启用 Cors 时收到此错误?

【问题讨论】:

  • 您是否在后端的 post 和 options 请求中启用了 cors?还是仅在请求后? (mentiosn preflight 请求是在真正的 post-request 之前发送的选项请求)。我看到您有 methods: "*",但如果将其添加到仅发布资源中,这将无济于事。
  • 你能举个例子吗?现在我有 config.EnableCors();在我的 WebApiConfig.cs 中。它应该在其他地方启用吗?
  • 我不是 C# 人,但这似乎是后端的问题。由于某种原因,cors 没有正确启用。我们将不得不查看更多后端代码来解释原因。
  • 可能问题出在“*”语法上。尝试明确启用所有内容。
  • * 应该被允许。我认为我需要配置这个预检请求?

标签: angularjs asp.net-web-api cors


【解决方案1】:

试试这个配置。

cors:
    allowed-origins: "*"
    allowed-methods: GET, PUT, POST, DELETE, OPTIONS
    allowed-headers: "*"
    exposed-headers:
    allow-credentials: true
    max-age: 1800

【讨论】:

    猜你喜欢
    • 2015-09-01
    • 2023-04-04
    • 2014-07-06
    • 2017-04-11
    • 2022-07-28
    • 1970-01-01
    • 2014-01-24
    • 2020-02-13
    • 1970-01-01
    相关资源
    最近更新 更多