-1

I can't use ajax call API but postman call API is ok. I develop web API on .net core 2.2 and develop asp.net core MVC. Then I use ajax call to API url "https://localhost:44349" An error occurred in Figure 1.

API: EmployeeController

[HttpPost("CheckAuth")]
public IActionResult checkAuth(EmployeeLoginRequest req)
    {
        // logic
        return Ok(JsonConvert.SerializeObject(employeeLoginResponse));
    }

API: Startup

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseCors(
                options => options.WithOrigins("https://localhost:44320").AllowAnyMethod()
            );
            app.UseHttpsRedirection();
            app.UseMvc();
        }

WEB App: Index.cshtml

var data = {
                "username": $.trim($("#inputUsername").val()),
                "password": $.trim($("#inputPassword").val())
            };

            $.ajax({
                url: "https://localhost:44349/Employee/CheckAuth",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: data,
                success: function (data, textStatus, xhr) {
                    console.log(data);
                },
                error: function (xhr, textStatus, errorThrown) {
                    console.log(xhr);
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });

How do I fix it?

Remark API Url: https://localhost:44349 Web Url: https://localhost:44320

Figure 1

Rufio Rocco
  • 121
  • 1
  • 6

2 Answers2

0

You need to enable CORS to resolve this issue, Please follow below steps: https://www.c-sharpcorner.com/article/enabling-cors-in-asp-net-core-api-application/

If you already enabled it, then please check below url and try those steps. Missing token 'access-control-allow-headers' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel

0

Try changing to this:

app.UseCors(
    options => options.WithOrigins("https://localhost:44349").AllowAnyMethod()
);
cwalvoort
  • 1,851
  • 1
  • 18
  • 19