serviejs / popsicle

Simple HTTP requests for node and the browser
MIT License
246 stars 19 forks source link

Popsicle ignores passed in headers when using FormData as the body #124

Closed jordanranson closed 6 years ago

jordanranson commented 6 years ago

Hello, I'm having some trouble this morning with a multipart form upload. What I'm trying to do is upload some files to an API by passing a FormData object into the request as the body. Now, this works great until I try to add my own headers to the request. It seems any headers I add get completely ignored which is an issue because I need to pass a token in to authenticate the request.

Here is the code I'm trying to use:

popsicle.request({
  url,
  body: formData,
  method: 'POST',
  headers: {
    token
  }
})

Here are the request headers that are sent:

accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9,es;q=0.8,fr;q=0.7,pt;q=0.6
cache-control: no-cache
content-length: 10286
content-type: multipart/form-data; boundary=----WebKitFormBoundaryunB1KqgNwE0pvFxQ
origin: http://localhost:8080
pragma: no-cache
referer: http://localhost:8080/index
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36

You'll notice token is no where to be found. token is present when I don't pass in a FormData object as the body. Am I missing something?

blakeembrey commented 6 years ago

Can you ensure token is not undefined? Aside from that, I'm not sure - this part of the behaviour is really relying on how the browser works and it shouldn't be wiping out any headers.

jordanranson commented 6 years ago

@blakeembrey I'm so sorry. I created a JSFiddle with the same code and was able to get the proper keys in the header. After investigating further I discovered that a misplaced parenthesis was causing the token to be passed in as undefined to my API call. User error, you were right on the money! Thanks for the help!