make a http request with a custom body as form data in typescript

To make an HTTP request with a custom body as form data in TypeScript, we can use the axios library.

First, we need to install axios by running the following command in our project directory:

index.ts
npm install axios
18 chars
2 lines

Then, we can make a POST request with form data as the body by creating a FormData object and appending key-value pairs using the append() method. We can then use axios to send the POST request with the FormData object as the data parameter.

Here's an example code snippet:

index.ts
import axios from 'axios';

const formData = new FormData();
formData.append('username', 'johnDoe');
formData.append('password', 'secret');

axios.post('https://example.com/login', formData)
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.error(error);
  });
297 chars
14 lines

In this example, we create a FormData object and append two key-value pairs: username and password. We then send a POST request to https://example.com/login with formData as the data parameter.

Note that axios automatically sets the Content-Type header to multipart/form-data when FormData is used as the request body.

gistlibby LogSnag