Search code examples
typescriptmultipartform-data

Typescript Http request send form data


I want to send form-data. But request has no body attribute. How can I use request to send form-data?

import { request } from 'http';

const form = new FormData();
form.append('file', FILE);

const req = request(
                {
                    host : HOST,
                    port : '80',
                    method : 'POST',
                    path : PATH,
                    headers : form.getHeaders(),        
                },
                response => {
                }
            );


Solution

  • Honestly the http library in node is really low level and not super friendly to use. I'd consider looking at something like axios because it's much friendlier as a developer.

    If you're set on using http, then the official docs are useful, in particular for you request.write is the method you're looking for.

    Those same docs from nodejs provide worked examples for a post with either axios:

    const axios = require('axios')
    
    axios
      .post('https://whatever.com/todos', {
        todo: 'Buy the milk'
      })
      .then(res => {
        console.log(`statusCode: ${res.status}`)
        console.log(res)
      })
      .catch(error => {
        console.error(error)
      })
    

    or http:

    const https = require('https')
    
    const data = JSON.stringify({
      todo: 'Buy the milk'
    })
    
    const options = {
      hostname: 'whatever.com',
      port: 443,
      path: '/todos',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
      }
    }
    
    const req = https.request(options, res => {
      console.log(`statusCode: ${res.statusCode}`)
    
      res.on('data', d => {
        process.stdout.write(d)
      })
    })
    
    req.on('error', error => {
      console.error(error)
    })
    
    req.write(data)
    req.end()