Frontend code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EventSource Stream Example</title>
</head>
<body>
<h1>Real-time Updates</h1>
<div id="messages"></div>
<script>
const eventSource = new EventSource('http://127.0.0.1:8083/api/webflux?msg=hello');
eventSource.onmessage = (event) => {
const messageElement = document.createElement('div');
messageElement.textContent = event.data;
document.getElementById('messages').appendChild(messageElement);
};
eventSource.onerror = (event) => {
console.error("EventSource failed: ", event);
const errorElement = document.createElement('div');
errorElement.style.color = 'red';
errorElement.textContent = 'An error occurred, check the console for details.';
document.getElementById('messages').appendChild(errorElement);
};
</script>
</body>
</html>
Backend Code
@RestController
@RequestMapping("/api")
@Slf4j
@CrossOrigin
public class TestController {
@GetMapping(value = "/webflux", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> testFlux(String msg) {
return Flux.fromIterable(strings).interval(Duration.ofSeconds(1)).map(e -> e + " " + msg);
}
}
enter image description here
The program returned correctly.,Why can’t the onmessage method trigger?
eventSource.onmessage not work eventSource.onerror can work
zakary is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.