Home > Back-end >  Access to XMLHttpRequestfrom origin has been blocked by CORS policy: No 'Access-Control-Allow-O
Access to XMLHttpRequestfrom origin has been blocked by CORS policy: No 'Access-Control-Allow-O

Time:06-21

I am calling an API (asp.net web api) from Angular 9 but sometimes I am getting Cross origin error. The debugger is hitting the API method and it returns the values as expected but in the browser I am getting 500 status with Access-Control-Allow-Origin header issue. Also this error does displays always only sometimes in particular for some particular responses. so can anyone help me here? Here are some sample codes.

[Route("api/product/Selection")]
[HttpPut()]
public IHttpActionResult Selection(VOW.Api.ProjectManager.Models.IndustrialSilencer product, string currency, string markup, string userTier2Markup, string projectId)
        {
           //some code
            ISM.SelectOutput(ref output, product, currency, Convert.ToDouble(markup), Convert.ToDouble(userTier2Markup), projectInfo.ExchangeRate);
            return Ok(output);
        }





 
      const S = this.http.put<Silencer>(this.baseurl   "/Selection", product, opts).subscribe(r => {

        S.unsubscribe();

        observer.next(r);
        observer.complete();

      },
        e => {
          S.unsubscribe();
          observer.error(e); // because its not any http call
          observer.complete();
        },
        () => {
          S.unsubscribe();
        }
      );




public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

CodePudding user response:

CORS stands for Cross-Origin Resource Sharing. The problem is not in your (front-end) side but the "problem" is in the back-end side. They are blocking the adress from which you want to access the API. That's it. When they "unblock" or give you some key which you usually add at the end of an URL, the problem will be gone.

Hope this helps.

CodePudding user response:

I used to have this intermitent error and mine resolved by adding on the proxy.conf.json (on the root folder) the following data:

{
  "/api/*": {
    "target": "http://localhost:53648",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
  }
}

I added on target the url for the api and changeOrigin to true, also when I serve or build the app I have to do it like this.

ng serve webApp --proxy-config proxy.conf.json

But like on the comment before this one. Most of the CORS issues are backend related. this helped me because the backend was already working correctly.

  • Related