The javascript tries to fetch data from my spring boot api and gives back a "Failed to fetch" error everytime.
I'm sure the request reaches the api because for every click on submit I get the print statement, that i put in my get method, logged as it should. So something on the way back must be wrong.
Get method:
@RestController
@RequestMapping("/familyMember")
public class FamilyController {
private FamilyRepository familyRepository;
public FamilyController(FamilyRepository familyRepository) {
this.familyRepository = familyRepository;
}
@GetMapping("/id/{id}")
public FamilyMember getById(@PathVariable("id") Long id) {
Optional<FamilyMember> optional = familyRepository.findById(id);
if (!optional.isPresent()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
FamilyMember familyMember = optional.get();
System.out.println(id); //print statement to make sure api is reached
return familyMember;
}
Javascript code:
const url = 'http://localhost:4001/familyMember/';
submit.onclick = async() => {
const endpoint = url 'id/' input.value;
try {
const response = await fetch(endpoint); // error occures here because no code below is executed
output.style.color = 'green'; // to see if fetch continues(apparently it doesn't)
if (response.ok) {
output.innerHTML = await response.json();
}
} catch(error) {
output.innerHTML = error; // gives me "Failed to fetch" in the html
}
I'm not sure if the bug is on the server side or client side. The api gives me the correct information when I use curl in the terminal...so propably the js code?
Thanks in advance.
CodePudding user response:
Actually found the answer. Above @RestController I need the annotation @CrossOrigin
sothat the api allows requests from different origins than itself (in that case a html file).
@CrossOrigin
@RestController
@RequestMapping("/familyMember")
public class FamilyController {
...