Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
failed to fetch using spring api on localhost

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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 {
...
about 4 years ago · Juan Pablo Isaza Relatório

0

You should specify cross origin with an adress like "localhost:4001"

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda