简体   繁体   English

使用 Java 脚本从 Spring 引导 API 端点获取数据时出现问题

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

I work on web application and encountered an issue with fetching data from an endpoint using Java Script.我在 web 应用程序上工作,遇到了使用 Java 脚本从端点获取数据的问题。 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. response.ok 返回 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:这是 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.脚本和运行它的 HTML 文件都位于类路径中的 static 目录中。

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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM