send a post request with file nodejs in typescript

Here's an example of how to send a POST request with a file using the request-promise library in TypeScript:

index.ts
import rp from 'request-promise';
import * as fs from 'fs';

const formData = {
  file: fs.createReadStream('path/to/file.jpg') // replace with your file path
};

const options = {
  method: 'POST',
  uri: 'http://example.com/upload',
  formData: formData,
  headers: {
    'Content-Type': 'multipart/form-data'
  }
};

rp(options)
  .then(function (parsedBody) {
    console.log(parsedBody);
  })
  .catch(function (err) {
    console.error(err);
  });
454 chars
24 lines

In this example, we're using the request-promise library to make the request, and we're using the fs library to read the file we want to upload.

We create a formData object with a key of file and a value of the file stream that we read from the file.

We create an options object with the method set to POST, the URI set to the URL we want to POST the file to, the formData property set to the formData object we created earlier, and the Content-Type header set to 'multipart/form-data'.

Finally, we make the request using rp(options). If the request is successful, the function passed to the then() method will be called with the response body, and if there's an error, the function passed to the catch() method will be called with the error message.

gistlibby LogSnag