DEV Community

Thiago Marinho
Thiago Marinho

Posted on

8

Como criar requisição de Crud Básico em Javascript usando Fetch API

Para criar um CRUD (Create, Read, Update, Delete) usando a Fetch API do JavaScript, você pode seguir os seguintes passos:

1 - Crie uma função para fazer uma requisição GET para buscar os dados do servidor:

function getDados() {
  fetch('url-do-servidor')
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error(error))
}
Enter fullscreen mode Exit fullscreen mode

2 - Crie uma função para enviar dados ao servidor usando uma requisição POST:

function enviarDados(dados) {
  fetch('url-do-servidor', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(dados)
  })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
}

Enter fullscreen mode Exit fullscreen mode

3 - Crie uma função para atualizar dados no servidor usando uma requisição PUT:

function atualizarDados(id, dados) {
  fetch(`url-do-servidor/${id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(dados)
  })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
}

Enter fullscreen mode Exit fullscreen mode

4 - Crie uma função para deletar dados no servidor usando uma requisição DELETE:

function deletarDados(id) {
  fetch(`url-do-servidor/${id}`, {
    method: 'DELETE'
  })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error))
}

Enter fullscreen mode Exit fullscreen mode

5 - Use as funções criadas para interagir com o servidor, por exemplo:

// Busca os dados do servidor
getDados()

// Envia novos dados para o servidor
enviarDados({ nome: 'João', idade: 25 })

// Atualiza os dados do servidor com id = 1
atualizarDados(1, { nome: 'Maria', idade: 30 })

// Deleta os dados do servidor com id = 2
deletarDados(2)

Enter fullscreen mode Exit fullscreen mode

Lembre-se de substituir "url-do-servidor" pela URL correta do seu servidor e adaptar as funções para atender às necessidades específicas do seu projeto.

Provavelmente você obterá um erro do browser relacionado ao CORS, se ocorrer utilize a biblioteca: https://github.com/expressjs/cors se o backend foi feito em Node.js, caso contrário busque outra solução.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay