猿问

如何修复 Angular/.NET 项目中的“跨源请求被阻止:同源策略不允许读取远程资源”

当我向我们的 API 端点提交 HTTP GET 请求时,我收到错误消息,指出缺少 CORS 标头“Access-Control-Allow-Origin”。


我们有一个连接到带有 Angular 7 前端的 .NET API 的 SQL Server 数据库。


这是提交请求的 Angular 服务


public VALUES_API_ENDPOINT = 'http://localhost:53273/api/search';


  constructor(private httpClient: HttpClient) { }


  async queryResults(terms: string): Promise<any> {

    try {

      const result = await this.httpClient.get(this.VALUES_API_ENDPOINT + '/title/' + terms).toPromise();

      return result;

    } catch (error) {

        await this.handleError(error);

    }

  }

后端控制器调用如下所示:


[HttpGet]

[Route("title")]

public HttpResponseMessage SearchByTitle(string s)

{

   HttpResponseMessage response;

   try

   {

       List<Regulation> results = search.SearchRegulationByTitle(s);

       string json = CondensedRegulationsToJson(results);

       response = Request.CreateResponse(HttpStatusCode.OK);

       response.Content = new StringContent(json, Encoding.UTF8, "application/json");

   }

   catch (Exception)

   {

       response = Request.CreateResponse(HttpStatusCode.InternalServerError);

   }

   return response;

}

我们的 API 配置如下所示:


public static void Register(HttpConfiguration config)

{

   // Web API configuration and services

   // Web API routes


   config.MapHttpAttributeRoutes();


   config.Routes.MapHttpRoute(

         name: "DefaultApi",

         routeTemplate: "api/{controller}/{id}",

         defaults: new { id = RouteParameter.Optional }

   );


   // Enable CORS for the Angular App

   // NOTE: Since we are running both the frontend and the backend locally, we can trust this origin with all headers and methods (the *). In practice, we would only allow really needed headers and methods

    config.EnableCors(new EnableCorsAttribute("http://localhost:4200", "*", "*", "*"));


  // Make JSON the default formatter over XML

  config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

            config.Formatters.Remove(config.Formatters.XmlFormatter);

}

我们应该从数据库接收数据,但我们只是根据 CORS 属性被拒绝访问。

牛魔王的故事
浏览 119回答 1
1回答

慕婉清6462132

您的 api 网址不正确:您还有其他/new/导致 404 错误的原因。从 api url中取出/new,问题应该得到解决。&nbsp;const&nbsp;result&nbsp;=&nbsp;await&nbsp;this.httpClient.get(this.VALUES_API_ENDPOINT&nbsp;+&nbsp;'/title/'&nbsp;+&nbsp;terms).toPromise();
随时随地看视频慕课网APP
我要回答