Issues encountered while accessing REST in Angular 6 due to Access-Control-Allow-Origin restrictions

I am currently facing an issue with loading data from a REST source into my Angular 6 app using http: HttpClient from '@angular/common/http'. When I try to call the app in the browser using ng serve --open, it seems like CORS is causing a problem. I have tried various ways to tackle this by setting server or client headers with Access-Control-Allow-Origin, but so far, I haven't been successful in making this REST call work. Below is the code snippet of what I have implemented.

Upon calling the Angular app in the browser, I receive the following error:

Failed to load http://localhost:8080/mysite-backend/rest/report/single/d83badf3: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested 
resource. Origin 'http://localhost:4200' is therefore not allowed 
access.

Interestingly, when I directly input the URL (

http://localhost:8080/mysite-backend/rest/report/single/d83badf3
) in the Chrome browser, it works perfectly fine giving me the expected JSON response:

{"id":"d83badf3","language":"en","categoryId":"a5","title":"Simcity","created":1527723183880,"modified":1527723183880}

In Angular 6, I have created a service class generated through ng generate service tour. Within this class, there's a method getTour(id: string) that simply makes a call to the specified URL and returns the retrieved JSON-string as a Tour object:

[Service Class Code Here]

The corresponding Tour object looks like this:

[Tour Object Code Here]

To resolve this CORS issue, I have also imported HttpClientModule from '@angular/common/http' in both the imports and providers arrays within app.module.ts.

On the backend side, the RESTful WebService is built in Java. The relevant part of the code includes the

getReport(@PathParam("reportId") String reportId)
method which retrieves a Report object and returns it within a Reponse:

[Java WebService Code Here]

What steps should I take to ensure a successful call from the Angular 6 client to the Java RESTful WebService?

Answer №1

The root of the problem is not in Angular itself, but rather in the web server being used.

Whenever an HTTP client request is made in Angular, it always sends a preflight request of type OPTIONS before proceeding with the actual request.

You may need to include the OPTIONS request method in this line:

   .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")

Answer №2

After spending the entire day trying to solve the issue, I initially believed it was related to Angular. However, upon further investigation, it became clear that the problem actually stemmed from the server side. The solution involved adding an @CrossOrigin annotation above the get method.

@GET
@CrossOrigin(origins = "http://localhost:4200")
@Path("/single/{reportId}")
public Response getReport(@PathParam("reportId") String reportId) {
    //return Mock.getReport(reportId);
    return Response.ok() // 200
                   .entity(Mock.getReport(reportId))
                   .header("Access-Control-Allow-Origin", "*")
                   .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
                   .allow("OPTIONS").build();
}

Answer №3

I spent nearly an entire day troubleshooting a client-side Angular application, only to realize that the issue was actually on the server side with the Node.js application needing to allow CORS.

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

Answer №4

I successfully resolved the CORS issue by using a proxy.

  1. To begin, create a file named proxy.conf.json at the same level as your package.json file.
  2. Add the following content:

{
    "/api/*": {
        "target": "http://external-domain-you-wanted-to-access",
        "secure": false,
        "changeOrigin": true
    }
}

  1. Use the command ng serve --proxy-config proxy.conf.json to run the proxy setup.

More information can be found in this reference link.

Answer №5

Here are the steps that helped me to solve the issue:

1- Make sure to create a file named proxy.conf.json in the root of your project, rather than the src folder.

2- Copy and paste the following code into the proxy.conf.json file:

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false
  }
}

3- Add the line below in your package.json file under scripts:

"start": ng serve --proxy-config proxy.conf.json

4- When starting the application, use npm start instead of ng serve.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the parent route component in Angular

I am in the process of developing an Angular 7 application that features nested routes. My goal is to identify the specific component being used by the parent route. While I have managed to achieve this locally, the method fails in a production environment ...

Implementing Dynamic Columns and Rows in GridLayout using NativeScript

My HTML code consists of two GridDatas and two buttons. When Button1 is pressed, gridData1 should be displayed, and when Button2 is pressed, gridData2 should be displayed. The number of rows and columns remains static. Here are the TypeScript snippets: g ...

Developing a cutting-edge project: Integrating Angular with PrimeNG to create a dynamic Sakai skeleton demo

I have just cloned the Sakai angular skeleton repository from this location: git clone https://github.com/primefaces/sakai-ng.git In the default setup, the 'landing' URL is set to the Sakai demo. However, I would like my base URL to point to my ...

Error: The value entered for the 'end_time' column in row 1 is outside of the acceptable range

My current scenario involves sending a JSON payload from an Android device to a web-service. The JSON includes two fields, namely startTime and endTime. Both startTime and endTime are of type Long in the DTO classes on both the client and server sides. How ...

"What are the necessary components to include in UserDTO and what is the reasoning behind their

Presenting the User entity: package com.yogesh.juvenilebackend.Model; import jakarta.annotation.Generated; import jakarta.persistence.*; import lombok.*; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @RequiredArgsConstructor public class ...

Tips to store Google fonts in the assets directory

I've included this link in my styles.scss @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap'); While it works locally, the API fails on production or is blocked. How can I host it within my p ...

Error message: org.apache.jorphan.util.JMeterException: Unable to execute bsh method: evalSourced script: inline evaluation of:

After upgrading from selenium-server-standalone-2.53.0 to selenium-server-standalone-3.1.0 in the %Jmeter%lib folder, I encountered the following error: Response message: org.apache.jorphan.util.JMeterException: Error invoking bsh method: eval Sourced fil ...

Showing a dynamically updated array in Angular

Within my Angular Application I am utilizing an ngFor loop in the component to display an array. Now, I am filtering the data from the array and aiming to update the newly filtered array in place of the original one. While I can successfully display the ...

Having difficulty grasping the significance of the data received from the API response

Currently, as I am working on my personal Portfolio for a Web Developer course, I have encountered an issue with correctly implementing my API to retrieve information from the database. Previously, I faced no problem when using a .json file, but now, I am ...

Modify the color of the Swing link label for disabled state

I'm currently working with Java Swing linkLabel. I've noticed that when the link is disabled, it appears in gray by default, but I would like it to be black instead. Is there a method available to change the color of a disabled link label? ...

Issue encountered when using Angular CLI to generate new files in the current directory

I've encountered an issue where, when using Angular CLI to generate components, it places them in the App folder instead of the current directory. For example, if I navigate to App/Recipe and run "ng g c recipe-item", the component will be generated i ...

Using Angular, you can easily add a <div> dynamically to all elements that share a class

In order to implement a solution, I am tasked with adding a new div element with the class '.cart-list-value .delete-product', which will contain a background image, to all elements that have the class .cart-list-item. Although I successfully man ...

Showing numeric values with decimals in an Angular Handsontable table

I want to display a decimal value (22.45) without rounding while using angular-handsontable in my application. Even though I specified the format, the value is not displayed as expected columns: ({ type: string; numericFormat: { pattern: string; }; } | {} ...

Angular: Smooth transitions for ngif animations - Learn how to animate ngif elements seamlessly as one element is removed from the DOM

Is there a way to delay the execution of ngIf? I have a scenario where elements in a parent component fade out and are removed from the DOM using ngIf, followed by elements from a child component coming in. However, I am facing an issue with elements overl ...

Automated test does not trigger Selenium Webdriver modal popup

Currently, I am developing automation scripts using Selenium Webdriver in Java to test an application designed for Point of Sale systems. Upon the initial launch of the application, a modal dialog box is displayed for the user to make a selection. This mo ...

Changing row colors based on property conditions in Angular 4

Hey there! I'm fairly new to Angular 4 and I've been working on creating a p-dataTable. My goal is to change the color of each row based on the quantity property of my object. Specifically, if the quantity is less than 10, I want the row to be di ...

Customizing the Global Error Handler in Angular

Our project utilizes a global error handler to manage errors. However, we have encountered a unique scenario where we need to handle a specific case separately but are unable to do so. The global error handler is configured in the app.module.ts: { provide: ...

Navigating the correct way to filter JSON data using HttpClient in Angular 4

Struggling with transitioning from Http to HttpClient, here's the code in question: constructor(public navCtrl: NavController, public http: HttpClient, private alertCtrl: AlertController) { this.http.get('http://example.com/date.php') .su ...

What is the process for an Angular Component to receive a return object from a service following an HTTP

I am currently working with angular 4. Is there a way to retrieve an object from a service in this framework? export class LoginRequest { username : string; password : string; } export class LoginResponse { token : string; message : string; sta ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...