matthew-andrews / isomorphic-fetch

Isomorphic WHATWG Fetch API, for Node & Browserify
MIT License
6.95k stars 289 forks source link

How to POST with application/x-www-form-urlencoded header and URLSearchParams #130

Closed amalv closed 7 years ago

amalv commented 7 years ago

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?

PS: If any one knows a public REST API which requires the application/x-www-form-urlencoded header I can provide a better example in order to reproduce this error and / or being able to better debug it.

amalv commented 7 years ago

So it seems the problem was that the Content-Length header is required with the application/x-www-form-urlencoded header.