The "Cross-Origin Request Blocked" error occurs when a web application running in one domain (origin) attempts to make an HTTP request to a different domain (origin), and the browser blocks the request due to security reasons. This is known as the Same-Origin Policy, a security feature implemented by web browsers to prevent unauthorized access to resources on other domains.

To resolve the "Cross-Origin Request Blocked" error in an Angular 5 application using HttpClient, you can take one of the following approaches:

  1. Enable CORS on the Server: If you control the server that your Angular application is making requests to, you can enable Cross-Origin Resource Sharing (CORS) on the server to allow requests from specific origins. You need to configure the server to include the appropriate CORS headers in its responses.

  2. Use a Proxy Server: Set up a proxy server on your own domain that forwards the requests to the target server. This way, the requests are made from the same origin as your Angular application, and the "Cross-Origin Request Blocked" error is avoided. You can use the proxy.conf.json file with Angular CLI to configure the proxy.

  3. JSONP (For GET Requests Only): If the API you are accessing supports JSONP, you can use JSONP for GET requests. JSONP bypasses the Same-Origin Policy by making requests using <script> tags, which are not subject to cross-origin restrictions.

  4. Server-Side Proxy (For Production): In a production environment, you can set up a server-side proxy using technologies like Nginx or Apache. The proxy server forwards the requests to the API, and your Angular application communicates with the proxy server, avoiding the cross-origin issue.

Here's how you can use the proxy approach in an Angular 5 application:

  1. Create a proxy.conf.json file in the root of your Angular project with the following content:
{ "/api": { "target": "", // Replace with the target API URL "secure": false, "changeOrigin": true } }
  1. In the angular.json file, add the proxyConfig option under the "architect" > "serve" configuration:
"serve": { "builder": "@angular-devkit/build-angular:dev-server", "options": { "browserTarget": "your-app:build", "proxyConfig": "proxy.conf.json" }, "configurations": { "production": { "browserTarget": "your-app:build:production" } } },

Replace "your-app" with the name of your Angular app in the angular.json file.

  1. Start the development server with the --proxy-config option:
ng serve --proxy-config=proxy.conf.json

Now, when you make HTTP requests to /api in your Angular application, they will be forwarded to through the proxy, avoiding the "Cross-Origin Request Blocked" error.

Remember that while the proxy approach works well during development, in production, it is recommended to set up a server-side proxy for security and performance reasons.

Have questions or queries?
Get in Touch