Enable CORS in ASP .NET Core 2.1 Web Api

牧云@^-^@ 提交于 2019-12-11 10:45:36

问题


I'm writting application in ASP .NET Core 2.1 Web API and React. I have my server on localhost:5000 and my client on localhost:3000. I wanted to send post request with axios but in browser console i see error:

OPTIONS https://localhost:5001/api/auth/login 0 ()
Uncaught (in promise) Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:87)

In my Web API I try to add CORS but it doesn't seems to work. I add:

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

And:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors(options =>
        options
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());
    ...
    app.UseMvc();
}

And this is my post request:

const response = await axios({
        method: 'post',
        url: 'http://localhost:5000/api/auth/login',

        data: {
            userName: this.state.controls.login.value,
            password: this.state.controls.password.value
        }
    });

Server console after request:

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 OPTIONS http://localhost:5000/api/auth/login
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
      Policy execution successful.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 4.253ms 204
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 POST http://localhost:5000/api/auth/login application/json;charset=UTF-8 52
info: Microsoft.AspNetCore.Cors.Infrastructure.CorsService[4]
      Policy execution successful.
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 2.1805ms 307
info: Microsoft.AspNetCore.Server.Kestrel[32]
      Connection id "0HLG4CH3JIV16", Request id "0HLG4CH3JIV16:00000002": the application completed without reading the entire request body.

When I use Postman everything is fine. I receive json with token from server.


回答1:


Ok, I resolve my problem. I just don't know that I should remove "app.UseHttpsRedirection();".



来源:https://stackoverflow.com/questions/51900055/enable-cors-in-asp-net-core-2-1-web-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!