简体   繁体   中英

CORS Issue with Angular 10 and net6.0 API project

From angular project when I send to GET request in my backend it works fine but if I send POST request with body that time it's not work.

Angular Code

    login(email: string, password: string) {        
    return this.http.post<any>(`${baseUrl}/authenticate`, { email, password }, { withCredentials: true })
        .pipe(map(account => {
            this.accountSubject.next(account);
            this.startRefreshTokenTimer();
            return account;
        }));
    }

.Net Controller Code

    [HttpPost("authenticate")]
    public ActionResult<AuthenticateResponse> Authenticate(AuthenticateRequest model)
    {
        var response = _accountService.Authenticate(model, ipAddress());
        setTokenCookie(response.RefreshToken);
        return Ok(response);
    }

In controller top added below flag

[ApiController]
[Route("[controller]")]
[EnableCors("AllowOrigin")]

And added cors allow code in my Program.cs

app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());

In my Browser console show this error

在此处输入图像描述

What am I missing?

According the documentation, You have two options to allow any origin. Use the wildcard *. https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0

   builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
    {
        builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
    }));
    
    if (app.Environment.IsDevelopment())
    {
        app.UseSwagger();
        app.UseSwaggerUI();
    
    }
    //app cors
    app.UseCors("corsapp");

OR

app.UseCors(
  options => options.WithOrigins("*").AllowAnyMethod().AllowAnyHeader()
      );

Remove this from the methods

[EnableCors("AllowOrigin")]

Your requests are allowed only from certain domain, since you are firing request from "localhost" you are getting this error. Please ask api team to enable CORS for this to work.

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