Problem with fetching data from Spring Boot API endpoint using Java Script

Tags: , , , ,



I work on web application and encountered an issue with fetching data from an endpoint using Java Script. If I type endpoint adres in a browser it works perfectly fine but somehow it does not work in the script. The response.ok is returns False.

Here is script:

(function() {

    function requestAuthorization() {
        let response = fetch("http://localhost:8080/authorizationData")
            .then(response => response.json());

        if (response.ok) {
            let json = response.json();
            alert(json);
        } else {
            alert("HTTP response not ok");
        }
    }

    requestAuthorization();

})();

Here is controller:

@RestController
class AuthController {

    private final AuthService service;

    AuthController(AuthService service) throws IOException {
        this.service = service;
    }

    @GetMapping("/authorizationData")
    public ResponseEntity<AuthData> authorize() throws IOException {
        return ResponseEntity.ok(service.getAuthData());
    }
}

Here is service:

@Service
class AuthService {

    private final ObjectMapper mapper;

    AuthService(ObjectMapper mapper) {
        this.mapper = mapper;
    }

    public AuthData getAuthData() throws IOException {
        String resourcePath = "data/applicationSettings.json";
        InputStream resource = new ClassPathResource(resourcePath).getInputStream();
        return mapper.readValue(resource, AuthData.class);
    }
}

What is wrong? If You have any other advice regarding my work I will be pleased to hear it.

EDIT

The script and and HTML file which runs it are both located in static directory in classpath.

Answer

You should be doing it like this:

// mark your function as async
async function requestAuthorization() {
    // always try using const rather than let
    const response = await fetch("http://localhost:8080/authorizationData");

    if (response.ok) {
        const json = response.json();
        alert(json);
    } else {
        alert("HTTP response not ok");
    }
}


Source: stackoverflow