Dino Geek, try to help you

How to make HTTP requests (GET POST PUT DELETE) in JavaScript?


JavaScript can make HTTP requests through various methods, including the `fetch` API, `XMLHttpRequest` etc.

Here’s how you can make HTTP request using the fetch API:

1. GET request:

```
fetch(‘https://api.example.com/data’, { method: ‘GET’,
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => { console.error(‘Error:’, error);
});
```

2. POST request:

```
fetch(‘https://api.example.com/data’, { method: ‘POST’, headers: { ‘Content-Type’: ‘application/json’, }, body: JSON.stringify({key: ‘value’}),
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => { console.error(‘Error:’, error);
});
```

3. PUT request:

```
fetch(‘https://api.example.com/data/1’, { method: ‘PUT’, headers: { ‘Content-Type’: ‘application/json’, }, body: JSON.stringify({key: ‘value’}),
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => { console.error(‘Error:’, error);
});
```

4. DELETE request:

```
fetch(‘https://api.example.com/data/1’, { method: ‘DELETE’,
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => { console.error(‘Error:’, error);
});
```

Note: `fetch()` returns a Promise that resolves to the Response to that request, whether it is successful or not. You have to convert this response to text, json etc to handle this data as needed.

Also, be aware of CORS (Cross-Origin Resource Sharing) policies when making HTTP requests in JavaScript: if you request a resource from a different domain, you might get blocked by the same-origin policy.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use