3

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?

rfc1484
  • 9,441
  • 16
  • 72
  • 123
  • 1
    I don't know about isomorphic-fetch, but I do know about the Fetch Standard and it requires the user agent to set the Content-Length header for these kind of requests. (You also don't have to set Content-Type yourself, the user agent should take care of that too.) – Anne Apr 10 '17 at 14:37
  • You are right, I guess I was confused because in the CURL request there was no need to specify the `Content-Length` header. May be you can write the comment as an answer? – rfc1484 Apr 10 '17 at 15:52

1 Answers1

3

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.)

Anne
  • 7,070
  • 1
  • 26
  • 27