How to Send Data to API in JavaScript Node – Best Practices? or What’s the Right Way to Send Data to

20 Replies, 607 Views

Dude, error handling is key for how to send data to api in javascript node. Here’s how I do it with `axios`:

```javascript
try {
const res = await axios.post('/api', { data });
console.log(res.data);
} catch (err) {
if (err.response) {
// Server responded with a status outside 2xx
console.log(err.response.data);
} else if (err.request) {
// No response received
console.log('Network error?');
} else {
// Something else broke
console.log('Uh oh:', err.message);
}
}
```

This pattern saves me every time.

Messages In This Thread



Users browsing this thread: 1 Guest(s)