0

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.

1
  • 1
    The fetch API returns a Promise. Therefore, it is asynchronous. Therefore, when you access response.ok, the promise has most likely not resolved yet. Add async to your function and await to the call to the fetch API to resolve the issue. Otherwise you can put your if-clause directly into the then block and it will work as well. Does that resolve your issue? Commented Jan 4, 2021 at 19:09

1 Answer 1

1

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");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.