Spring + Angular: How to parse ResponseEntity in angular?

Viewed 12152

I'm using Spring Boot to create an API that needs to be consumed in Angular 4. Spring and Angular are on different ports.

The problem is that Spring's ResponseEntity raises an error in Angular.

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity getFlow(@PathVariable int id) {
        Flow flow = flowService.findById(id);

        return new ResponseEntity(flow, HttpStatus.FOUND);
    }

Now, I can perfectly use Postman to test the API and it works. enter image description here

But when I make a request from Angular, it returns an error: enter image description here

enter image description here

Strangely, it returns an error alongside the requested object.

Now, the cause of the problem is that the Spring Boot application returns a ResponseEntity and not a normal object (like String), and Angular doesn't know how to interpret it. If the controller returns just a Flow object, it works.

How can it be solved using ResponseEntity? Or, how else can I send the object alongside the HTTP status code?

2 Answers

Also, in @RequestMapping put produces = "application/json", and in get request in angular, add http options :

const httpOptions = {
    headers: new HttpHeaders({
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    })
};

So your get request looks like this:

this.http.get(url, httpOptions)
Related