简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM