[英]Problem with fetching data from Spring Boot API endpoint using Java Script
我在 web 应用程序上工作,遇到了使用 Java 脚本从端点获取数据的问题。 如果我在浏览器中输入端点地址,它工作得很好,但不知何故它在脚本中不起作用。 response.ok 返回 False。
这是脚本:
(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();
})();
这是 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());
}
}
这里是服务:
@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);
}
}
怎么了? 如果您对我的工作有任何其他建议,我将很高兴听到。
编辑
脚本和运行它的 HTML 文件都位于类路径中的 static 目录中。
你应该这样做:
// 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.