typicode / fetchival

Easy window.fetch requests
MIT License
522 stars 33 forks source link

Support custom headers #2

Closed leonderijke closed 9 years ago

leonderijke commented 9 years ago

Currently, the request headers are fixed by:

opts.headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}

It would be nice to support extra/custom headers. For example:

opts.headers = Object.assign({}, {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
}, opts.headers);

This would support overridding the default headers, but Object.assign would need to be polyfilled in a lot of browsers.

What do you think?

typicode commented 9 years ago

Hmm, seems great except for the polyfilled part. I don't see what other headers could be added? Do you have any examples?

leonderijke commented 9 years ago

Custom headers prefixed with X-, for example: X-Access-Token. Or if you need to POST with a different Content-Type, like application/x-www-form-urlencoded.

typicode commented 9 years ago

You're right. Working on something.

typicode commented 9 years ago

It took a little time, but here it is in v0.2.0. You can pass fetch options as a second argument to fetchival()

var request = fetchival('/', {
  // fetch options
  headers: {
    'X-SOME-HEADER': 'foo'
  }
})

// subsequent call to request will inherit previous fetch options
var posts = request('posts')

// you can add other options too
// will have X-SOME-HEADER and be in CORS mode
var users = request('users', { mode: 'cors' }) 

fetchival() signature has changed also:

fetchival('posts', 1, 'comments') // KO in v0.2.0
fetchival('posts/' + 1 + '/comments') // OK