0

I am learning Front End with Angular and Back End with Spring Boot right now and I am having issues when I try to fetch data from the Back End.

Angular Code:

ngOnInit() {

    this.http.get('http://127.0.0.1:8081/products').toPromise().then((data) => {
      console.log(data);
    });
  }

The Back End is working just fine, because I tried getting data with Postman and it works just fine.

postman get request image

Also copied the URL(http://127.0.0.1:8081/products) directly into my browser and it works just fine.

enter image description here

But when i try to request data from for example from JSONPlaceholder it works fine with the angular http get function.

ngOnInit() {

    this.http.get('http://jsonplaceholder.typicode.com/todos/1').toPromise().then((data) => {
      console.log(data);
    });
  }

result of the JSONPlaceholder request:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

I hope this extra information helps you to help me.

Last but not least the error message I get:

error message

ssdu05
  • 23
  • 4
  • 1
    Have you heard about CORS? – Lemmy Feb 16 '20 at 22:53
  • 2
    In short, your website (client) is working on some origin (e.g. `localhost:4200`), and it's making a request to a different origin (e.g. `localhost:8081`). By default, most servers do not accept requests from foreign origins. Check this for more information on enabling CORS in Spring: https://stackoverflow.com/questions/51720552/enabling-cors-globally-in-spring-boot – Marian Feb 16 '20 at 22:57
  • Angular runs on client side, therefore, you must add permission to your host by enabling CORS on your server side – RicardoVallejo Feb 16 '20 at 22:58
  • 1
    Does this answer your question? [Why doesn’t Postman get a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error when my JavaScript code does?](https://stackoverflow.com/questions/20035101/why-doesn-t-postman-get-a-no-access-control-allow-origin-header-is-present-on) – Marian Feb 16 '20 at 23:01

1 Answers1

0

Thanks for all the help guys, and I found the answer for all the people having a similar problem.

So basically i forgot to add this annotation to the rest controller in the back end.

@CrossOrigin(origins = "*", maxAge = 3600)
ssdu05
  • 23
  • 4