elbywan / wretch

A tiny wrapper built around fetch with an intuitive syntax. :candy:
MIT License
4.83k stars 98 forks source link

Get response headers #39

Closed mvasin closed 5 years ago

mvasin commented 5 years ago

Hi and thanks for the awesome lib!

Is there a way to get response headers when using wretch? I wasn't able to find anything in the docs.

elbywan commented 5 years ago

Hi and thanks for the awesome lib!

Hi @mvasin, thanks!

Is there a way to get response headers when using wretch? I wasn't able to find anything in the docs.

Yes, you can get the headers them by using .res() to retrieve the raw fetch response object.

// see it in action here: https://runkit.com/embed/ydiucqoe45xu

wretch('...').get().res(res => {
    // 'res' is the raw response (see https://developer.mozilla.org/en-US/docs/Web/API/Response)
    // 'res.headers' contains the Headers (https://developer.mozilla.org/en-US/docs/Web/API/Headers)
    console.log(Array.from(res.headers.entries()))
    return res.text()
}).then(console.log)
kuzyo commented 5 years ago

What is the best way to pass headers further alongside with json data to resolve in then block ?

const successHandler = response => {
    console.log({response})
    if (response.status === 201) {
      let authToken = response.data["auth-token"];
      let { client } = response.data;
      let sessionCookie = response.headers["set-cookie"][0];

      onSuccess(authToken, sessionCookie, client);
    } else {
      errorHandler();
    }
  };
mrchief commented 5 years ago

If you need both headers and the json data, here's how I did it:

.res(response => {
    // do something with response.headers
    return res.json(); // or res.text() if you need text
})
.then(json => {...})
lellky commented 4 years ago

I had the same question myself and just wanted to att that this works response.headers.get('location')