Raj Parekh
Raj Parekh

Reputation: 94

Spring boot rest endpoint returning null with fetch request

I have already created Rest Endpoint in Java spring boot. It returns appropriate response when I request it via Postman. But when I use react fetch it does not show any response in browser if return is Json.

Spring boot controller:

@RestController
@RequestMapping(path = "/v1/test")
@AllArgsConstructor(onConstructor_ = {@Autowired})
public class TestController {
    ...
}

Below endpoint is returning appropriate response.

  @GetMapping(value = "/helloWorld", produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseStatus(HttpStatus.OK)
  public String getHelloWorld() {
    return "Hello, World1!";
  }

enter image description here

But when I try to hit below endpoint it returns null when I make fetch request. But it returns appropriate response when I hit it via postman.

  @GetMapping(value = "/testEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseStatus(HttpStatus.OK)
  public String returnTestResponse() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("results", "value2");
    return "{\"a\":1, \"b\":\"foo\"}";
  }

enter image description here

Also tried returning POJO object. But still no response.

  @GetMapping(value = "/testModel", produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseStatus(HttpStatus.OK)
  public SearchResultsModel testModel() {
    this.myService.getSearchResult();
  }

React fetch call:

await fetch(ALL_ARTICLES_ENDPOINT, {
    mode: 'no-cors', 
    method: 'GET',
    redirect: 'follow',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
  }).then(response => {
    console.log(response);
  })
  .then(data => {
    console.log('Success:', data);
  }).catch((error) => {
    console.error('Error:', error);
  });

Upvotes: 0

Views: 1941

Answers (2)

Raj Parekh
Raj Parekh

Reputation: 94

Issue was caused by adding mode: 'no-cors' option in fetch request. This option helped me to get rid of cors error but it means that in return I won't be able to see body and headers in chrome.

To resolve the issue I removed mode: 'no-cors' and added @CrossOrigin annotation on my spring boot controller.

Upvotes: 0

Krzysztof K
Krzysztof K

Reputation: 784

Postman have couple hidden headers which are being sent with all requests. Check Hide auto-generated headers

enter image description here

What you are missing in react call is is Accept header with application/json value

EDIT:

Just saw that you are returning string as json. You need to wrap it in POJO object and return it in returnTestResponse class

SECOND EDIT:

This will work. Try to implement your POJO

@GetMapping(value = "/testEndpoint", produces = MediaType.APPLICATION_JSON_VALUE)
  @ResponseStatus(HttpStatus.OK)
  public YourObject returnTestResponse() {
    HashMap<String, Object> map = new HashMap<>();
    map.put("key1", "value1");
    map.put("results", "value2");
    return new YourObject(map);
  }

Upvotes: 1

Related Questions