node.jscurlfetch-apiisomorphic-fetch-apihttp-status-code-411

How to POST with application/x-www-form-urlencoded header and URLSearchParams using isomorphic-fetch


This is a CURL example which works fine:

curl --request POST \
  --url <url> \
  --header 'authorization: Bearer <authorization token>' \
  --header 'content-type: application/x-www-form-urlencoded' \
  --data 'category=1&userId=<uuid>'

I'm trying to reproduce this request using isomorphic-fetch.

I've tried this:

const searchParams = new URLSearchParams();
searchParams.set('category', category);
searchParams.set('userId', userId);

return fetch(`<url>`, {      
  method: 'POST',
  headers: {
    'Authorization: Bearer <authorization token>',
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
  },
  body: searchParams
})`

But I get a 411 status code error response (length required)

More info about URLSearchParams and Fetch here:

fetch documentation

fetch spec

Any suggestions?


Solution

  • Assuming the server implementation is correct the problem here is with isomorphic-fetch (or much more likely, the underlying GitHub's WHATWG Fetch polyfill) in that it doesn't add the Content-Length header as it's required to for fixed-length bodies by the Fetch Standard.

    (You should also be able to omit the Content-Type header as that is also supposed to be inferred from the URLSearchParams object and added by the implementation of the API.)