【问题标题】:Angular $http.get call to web apiAngular $http.get 调用 web api
【发布时间】:2016-05-03 16:44:11
【问题描述】:

我有两个 Web 应用程序正在运行。 App1 是一个 Angular SPA,而 App2 是一个用 c# 编写的 MVC Web api。我正在从 Visual Studio 2015 执行这两个应用程序,在 IIS Express 中运行调试。

我的 Angular 代码 (App1) 正在尝试使用以下(调试)代码在 App2 中调用 api 控制器:

$http.get('https://localhost:12345/api/values').then(function (response) {
            alert(response.data);
        }, function (err) { 
            alert(err);
        }).catch(function (e) {
            console.log("error", e);
            throw e;
        }) .finally(function () {
            console.log("This finally block");
        });

我总是点击“alert(err);”行 - 它永远不会成功执行,并且 err 没有任何有用的信息来指示问题可能是什么。

在 Postman(Chrome 插件)中,我可以确认我尝试对 App2 进行的调用工作正常。我究竟做错了什么?这可能是 CORS 的问题吗?

提前致谢!

【问题讨论】:

  • 尽管err 没有任何有用的内容,但还是可以发布内容。此外,既然您已经在调试器中运行了两个站点,那么控制器操作是否真的会受到影响?
  • 方案是HTTPS。你确定没有身份验证问题?

标签: angularjs asp.net-mvc http cors http-get


【解决方案1】:

好的,我遇到的问题出在 web api (MVC 6 - ASP.net 5) 中,因为我必须允许来自我的 Angular 网站的请求。 startup.cs 文件添加了以下内容:

        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            services.AddCors();

            StartupInitialize(services);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseIISPlatformHandler();

            app.UseStaticFiles();

            app.UseCors(builder => builder.WithOrigins("http://localhost:12345/"));

            app.UseMvc();

            antiForgery = (IAntiforgery)app.ApplicationServices.GetService(typeof(IAntiforgery));
        }

【讨论】:

    【解决方案2】:

    您遇到 CORS/SAME ORIGIN POLICY 问题,可以在 Angular js 中找到有关它的一些信息:How to enable CORS in AngularJs
    这就是您在服务器站点中处理它的方式:http://docs.asp.net/projects/mvc/en/latest/security/cors-policy.html#cors-policy

    或者您最好在控制台选项卡中打开开发人员工具,并为我们提供有关您的代码中发生的事情的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-22
      • 2020-09-06
      • 2020-03-10
      • 1970-01-01
      • 2016-01-08
      • 1970-01-01
      相关资源
      最近更新 更多