0

I am calling Rest web api from angular 10.

Rest API links is up and running fine but when i call same from angular then it gives below error

Access to XMLHttpRequest at 'http://localhost:51664/api/values/forall' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I already have CORS line added in wepapiconfig.cs file.

PFA for details (CORS_Error.png and WebAPIConfig.png)

Prernq
  • 17
  • 1
  • 3
  • Does this answer your question? [No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API](https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe) – Jamshaid K. Aug 25 '22 at 13:56
  • You should add policy [This article helped me](https://stackoverflow.com/questions/63165649/angular-9-and-net-core-access-from-origin-localhost4200-has-been-blocked-by) – Khamidov Komil Aug 29 '22 at 09:11

1 Answers1

0

There is a better solution to use the PROXY in Angular to overcome CORS.

  1. Add a proxy.config.js file in the root folder.

enter image description here

const PROXY_CONFIG = [
  {
    context: [
      "/api"
    ],
    target: "http://localhost:8888",
    secure: false,
    logLevel: "debug",
    changeOrigin: true
  }
];

module.exports = PROXY_CONFIG;
  1. Add "proxyConfig": "proxy.config.js" in the angular.json file under the serve: So when u run ng serve the poxy will be added to the angular node lite server. enter image description here

  2. In your api call you have to call the api as http://localhost:4200/api/mydomain/path so from the browser it will be calling the apis in 4200, so the CORS err cannot come as now its calling the same domain. In the node lite server it will change the url to http://localhost:8888/mydomain/path and call the api as a server to server call. You can see the 'api' in the URL will be cut off by the proxy server and change the target as provided in the config.

j1s
  • 160
  • 2
  • 18