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

20 Replies, 618 Views

Ugh, 404s are the worst. 😤 For how to send data to api in javascript node, I’d recommend the `http` module if you want no dependencies, but it’s kinda verbose.

Here’s a barebones snippet:
```javascript
const http = require('http');
const data = JSON.stringify({ foo: 'bar' });

const req = http.request('http://api.example.com', {
method: 'POST',
headers: { 'Content-Type': 'application/json' }
}, (res) => {
let response = '';
res.on('data', (chunk) => response += chunk);
res.on('end', () => console.log(response));
});

req.on('error', (e) => console.error('RIP:', e));
req.write(data);
req.end();
```

Pro tip: Use `try/catch` if you’re mixing async/await!

Messages In This Thread



Users browsing this thread: 1 Guest(s)