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?
CodePudding user response:
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")]
CodePudding user response:
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.