-1

I've replaced request-promise with node-fetch. Everything works well except for one request, which sends form data to an endpoint that I, unfortunately, can't provide here. This is the code that works with request-promise:

const options = {
    method: 'POST',
    uri: keys.endpointUrl,
    formData: {
        operations: JSON.stringify(operations),
        map: JSON.stringify(map)
    },
    json: true
};

const response = await request(options);

After moving to node-fetch, it looks like so:

const FormData = require('formdata-node');

const form = new FormData();

form.set('operations', JSON.stringify(operations));
form.set('map', JSON.stringify(map));

const opts = {
    method: 'POST',
    body: form
};

const res = await fetch(keys.endpointUrl, opts);

console.log(res);

const response = res.json();

res is logged as:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      readable: true,
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: false,
      allowHalfOpen: true,
      _transformState: [Object],
      [Symbol(kCapture)]: false
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    status: 500,
    statusText: 'Internal Server Error',
    headers: Headers { [Symbol(map)]: [Object: null prototype] }
  }
}

I tried to add different headers but unfortunately, it keeps failing. What am I missing?

NodeJS: v12.16.1 node-fetch: 2.6.0

jz22
  • 2,328
  • 5
  • 31
  • 50

2 Answers2

1

My guess is you need to set the content-type header to x-www-form-urlencoded, which your endpoint is probably expecting. Note in the documentation:

The Content-Type header is only set automatically to x-www-form-urlencoded when an instance of URLSearchParams is given as such:

Dmitry Minkovsky
  • 36,185
  • 26
  • 116
  • 160
0

You don't need FormData unless you are uploading files

const fetch = require('node-fetch');

var form = {
  "operations": JSON.stringify(operations),
  "map": JSON.stringify(map)
}

const opts = {
    method: 'POST',
    body: form
};

const res = await fetch(keys.endpointUrl, opts);
Vinay
  • 7,442
  • 6
  • 25
  • 48