What's the best way to make a REST API request in JavaScript? or How do I properly handle a REST API

20 Replies, 1280 Views

Hey! Yeah, fetch() can be tricky at first. You *do* need to handle the response with .then() or use async/await—otherwise, the promise just hangs.

Common pitfall: forgetting to check response.ok or response.status before parsing JSON.

Here’s a quick example:
```javascript
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error('API fail');
return response.json();
})
.then(data => console.log(data))
.catch(err => console.error('Oops:', err));
```
For errors, always use .catch() or try/catch with await. Axios is a nicer lib if fetch feels clunky!

Messages In This Thread



Users browsing this thread: 1 Guest(s)