【问题标题】:I can't use ajax call api but postman call is ok我不能使用 ajax 调用 api 但邮递员调用没问题
【发布时间】:2019-09-22 17:14:20
【问题描述】:

我不能使用 ajax 调用 API,但邮递员调用 API 没问题。我在 .net core 2.2 上开发 web API 并开发 asp.net core MVC。然后我用ajax调用API url "https://localhost:44349" 出现错误,如图1。

API:员工控制器

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

API:启动

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 应用: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);
                }
            });

我该如何解决?

备注 API 网址:https://localhost:44349 网址:https://localhost:44320

【问题讨论】:

    标签: c# asp.net .net ajax asp.net-core


    【解决方案1】:

    试着改成这样:

    app.UseCors(
        options => options.WithOrigins("https://localhost:44349").AllowAnyMethod()
    );
    

    【讨论】:

      【解决方案2】:

      您需要启用 CORS 才能解决此问题, 请按照以下步骤操作: https://www.c-sharpcorner.com/article/enabling-cors-in-asp-net-core-api-application/

      如果您已经启用它,请检查以下网址并尝试这些步骤。 Missing token 'access-control-allow-headers' in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel

      【讨论】:

      • 您是否注意到 OP 确实在 .Net Core API(不是 web api 2)上启用了 CORS?
      猜你喜欢
      • 1970-01-01
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 2020-05-06
      • 1970-01-01
      • 2019-09-25
      • 2020-09-27
      相关资源
      最近更新 更多