run a curl request in typescript

To make a curl request in TypeScript, you can use either the default built-in fetch function or a third-party library such as axios.

Using Fetch:

index.ts
fetch('https://api.example.com/', {
  method: 'POST',
  body: 'data=example',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err));
245 chars
11 lines

Using Axios:

index.ts
import axios from 'axios';

axios.post('https://api.example.com/', { data: 'example' }, {
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(res => console.log(res.data))
.catch(err => console.log(err));
218 chars
10 lines

In either example, the URL being requested and the appropriate HTTP method (GET, POST, PUT, DELETE, etc.) should be filled in. Optionally, headers and request body can be included, depending on the requirements of the specific API endpoint being used.

gistlibby LogSnag