简体   繁体   中英

Angular $http.get call to web api

I have two web applications running. App1 is an angular SPA and App2 is an MVC web api written in c#. I am executing both applications from Visual Studio 2015, running debug in IIS Express.

My angular code (App1) is trying to call an api controller in App2 using the following (debug) code:

$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");
        });

I always hit the "alert(err);" line - it never successfully executes and err has nothing useful in it to indicate what the problem could be.

In Postman (addin for Chrome), I can confirm the call I'm trying to make to App2 works fine. What am I doing wrong? Could this be an issue with CORS?

Thanks in advance!

You either experiencing CORS/SAME ORIGIN POLICY issue that some information about it in angular js can be found here: How to enable CORS in AngularJs .
this is how you handle it in server site in your case: http://docs.asp.net/projects/mvc/en/latest/security/cors-policy.html#cors-policy

or you better open the developer tools in console tab and bring us some more information about what happened in your code.

Ok the problem I had was in the web api (MVC 6 - ASP.net 5) in that I had to allow the requests from my angular web site. The startup.cs file had the following added:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM