I have an application with .NET 7 and Angular 16 and i make a lot of requests from client to server and all works fine. My problem happens in a specific method that i am using to download a PDF file. Furthermore, this error only happens in production server. The error say (in the chrome console):
Access to XMLHttpRequest at 'http://10.17.40.93:5000/Report/GenerateEggResultsReport' from origin 'http://10.17.40.93:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Example of request that work:ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ
getUserResults(startDate: string): Observable<ResponseBase> {
const params = new HttpParams()
.set('startDate', startDate);
return this.http.get<ResponseBase>(environment.apiUrl + 'Report/getUserResults',
{
params,
headers: { 'LangInfo': this.baseService.currentLanguage.enumValue }
});
}
[HttpGet("GetUserResults")]
public JsonResult GetUserResults(DateTime startDate, DateTime endDate, bool isOptoClass, EShiftType? shiftType)
{
try
{
var eggResults = _machineReportAppService.GetUserResults(startDate, endDate, isOptoClass, shiftType);
return ResponseBase.StatusReturn(EReturnStatus.Success, eggResults);
}
catch (Exception ex)
{
var returnStatus = ex.Message == Translator.Translate("NoMachineOperationFound") ? EReturnStatus.CleanLoadedData : EReturnStatus.Error;
var returnMessage = !ex.Message.IsNullOrEmpty() ? ex.Message : Translator.Translate("ErrorGettingEggResults");
return ResponseBase.StatusReturn(returnStatus, returnMessage);
}
}
Example of request that don't work:
generateReportFile(eggResultsReportFileRequest: EggResultsReportFileRequest): Observable<HttpResponse<Blob>> {
return this.http.post<Blob>(environment.apiUrl + 'Report/GenerateEggResultsReportFile', eggResultsReportFileRequest, {
observe: 'response',
responseType: 'blob' as 'json',
headers: {
'Access-Control-Allow-Origin': '*',
'LangInfo': this.baseService.currentLanguage.enumValue
}
});
}
[HttpPost("GenerateEggResultsReportFile")]
public IActionResult GenerateEggResultsReportFile(EggResultsReportFileRequest eggResultsReportFileRequest)
{
try
{
CreateLog(eggResultsReportFileRequest);
var eggResultsReport = _machineReportAppService.GenerateEggResultsReportFile(eggResultsReportFileRequest);
return File(eggResultsReport.ReportContent, eggResultsReport.ReportExtension);
}
catch
{
throw new InvalidOperationException(Translator.Translate("ErrorGeneratingReport"));
}
}
The main difference I see between your examples is that one is a GET request and another is a POST request. CORS policies are different for GET and POST requests.
Perhaps this answer can be helpful: https://stackoverflow.com/a/64714974/11905918