typescript CORS问题:不存在“控制-允许-来源”标题

9vw9lbht  于 12个月前  发布在  TypeScript
关注(0)|答案(1)|浏览(121)

我在尝试从我的Angular应用程序向ASP.NET Core后端发出请求时遇到CORS问题。错误消息如下:从源“http://localhost:4200”访问"https://localhost:7289/cv/generate“处的XMLHttpRequest已被CORS策略阻止:对preflight请求的响应未通过访问控制检查:请求的资源上不存在”HTTP-Control-Allow-Origin“标头。详细信息:
问题描述:
我有一个Angular应用程序托管在'http://localhost:4200'上。后端是一个ASP.NET Core应用程序,端点位于'https://localhost:7289/cv/generate'。当试图从Angular应用程序向后端发出请求时,遇到了CORS问题。
错误详细信息:该错误发生在预检请求上,并且响应缺少“控制-允许-起源”标头。
尝试解决:我已检查后端CORS设置,但问题仍然存在。我已确保允许必要的HTTP方法。其他信息:
我也面临着类似的CORS问题与另一个端点:'https://localhost:7289/personalinfo'。
ASP.NET Core CORS配置:

services.AddCors(options =>
{
    options.AddPolicy("AllowAngularDev",
        builder =>
        {
            builder
                .WithOrigins("http://localhost:4200")
                .AllowAnyHeader()
                .AllowAnyMethod();
        });
});

// Use CORS
app.UseCors("AllowAngularDev");

字符串
Angular Service(personal-info.service.ts:

// personal-info.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { PersonalInfo } from './personal-info.model';
import { environment } from 'src/environment/environment';

@Injectable({
  providedIn: 'root',
})
export class PersonalInfoService {
  private apiUrl = environment.apiUrl;

  constructor(private http: HttpClient) {}

  getPersonalInfo(): Observable<PersonalInfo> {
    return this.http.get<PersonalInfo>(`${this.apiUrl}/personalinfo`);
  }

  createPersonalInfo(personalInfo: PersonalInfo): Observable<PersonalInfo> {
    return this.http.post<PersonalInfo>(`${this.apiUrl}/personalinfo`, personalInfo);
  }

  updatePersonalInfo(personalInfo: PersonalInfo): Observable<PersonalInfo> {
    const url = `${this.apiUrl}/personalinfo/${personalInfo.userId}`;
    return this.http.put<PersonalInfo>(url, personalInfo);
  }

  deletePersonalInfo(userId: number): Observable<void> {
    const url = `${this.apiUrl}/personalinfo/${userId}`;
    return this.http.delete<void>(url);
  }
}


ASP.NET核心控制器(CVController.cs):

using Microsoft.AspNetCore.Mvc;
using ResumeBuilder.Models;
using ResumeBuilder.Services;
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Cors; // Add this line for enabling CORS

namespace ResumeBuilder.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("AllowAll")] // Add this line to enable CORS
    public class CvController : ControllerBase
    {
        private readonly CvService _cvService;
        private readonly PdfService _pdfService;

        public CvController(CvService cvService, PdfService pdfService)
        {
            _cvService = cvService;
            _pdfService = pdfService;
        }

        [HttpGet]
        public IActionResult Get()
        {
            try
            {
                List<CV> cvs = _cvService.GetAllCvs();
                return Ok(cvs);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return StatusCode(500, "An error occurred while fetching CVs.");
            }
        }

        [HttpPost]
        public IActionResult Post([FromBody] CV cv)
        {
            try
            {
                // Extract individual components from the CV object
                Personalinfo personalInfo = cv.PersonalInfo;
                List<Education> educationList = cv.EducationList;
                List<WorkEx> workExperienceList = cv.WorkExperienceList;
                Skills skills = cv.CVSkills;

                // Call the SaveCv method with the extracted parameters
                _cvService.SaveCv(personalInfo, educationList, workExperienceList, skills);

                return Created("CV saved successfully", "CV saved successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return StatusCode(500, "An error occurred while saving the CV.");
            }
        }

        [HttpGet("download/{cvId}")]
        public IActionResult DownloadPdf(int cvId)
        {
            try
            {
                CV cv = _cvService.GetCvById(cvId);
                if (cv == null)
                {
                    return NotFound("CV not found");
                }

                // Generate a unique file name, e.g., based on CV's full name and current timestamp
                string fileName = $"{cv.PersonalInfo.FullName}_Resume_{DateTime.Now:yyyyMMddHHmmss}.pdf";
                string filePath = Path.Combine("wwwroot", "pdfs", fileName);

                // Generate the PDF and save it to the specified file path
                _pdfService.GeneratePdf(cv, filePath);

                // Return the file for download
                return PhysicalFile(filePath, "application/pdf", fileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return StatusCode(500, "An error occurred while generating the PDF.");
            }
        }
    }
}


如何解决此CORS问题并确保响应中存在“控制-允许-起源”标头?
我试图通过以下方式解决CORS问题:
1.在我的ASP.NETCore后端检查CORS配置。
2.确保允许必要的HTTP方法。
3.检查Angular HTTP请求头。
4.查看Angular和ASP.NET Core中CORS配置的相关文档。
我希望这些步骤可以解决这个问题,并且我可以从我的Angular应用程序向ASP.NET Core后端发出成功的请求。然而,尽管做了这些努力,CORS问题仍然存在,并且问题中提到的错误消息仍然出现。

hl0ma9xz

hl0ma9xz1#

1.做@GH DevOps在评论中说的事情
1.你什么时候叫USCors?你在USCors之前叫任何'use...'中间件吗?试着让它成为第一个中间件
1.也许可以尝试删除“addpolicy”并直接像上面那样配置:

var app = builder.Build();
// This must be first line after 'builder.build()' - no other middleware
app.UseCors(c => c.WithOrigins(new string[] { "http://localhost:4200" })
    .AllowAnyMethod()
    .AllowCredentials()
    .AllowAnyHeader())

字符串

相关问题