Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Any way to get the headers from the response in an interceptor? #297

Open
webera1979 opened this issue Oct 16, 2020 · 11 comments
Open

Any way to get the headers from the response in an interceptor? #297

webera1979 opened this issue Oct 16, 2020 · 11 comments

Comments

@webera1979
Copy link

webera1979 commented Oct 16, 2020

Hello,

is there any way to retrieve the headers from an response in the interceptor configuration?
I cannot find it, but I think I am missing something. Thanks, Andreas

const options = {
        interceptors: {
            request: async ({ options } : any ) => {


                return options
            },
            response: async ({ response } : any ) => {

                return response
            }
        }
    }
@iamthesiz
Copy link
Collaborator

Sorry for the delay. Should be response.headers

@iamthesiz
Copy link
Collaborator

We mimic new Response() with a builtin object. All the fields in new Response() should be in the response object.

@webera1979
Copy link
Author

Hi Alex,

thank you so much. No worries concerning the delay.

Having the headers in response.headers has been my expectation as well.

They are always empty though ( -> {}). Do you need an example to reproduce?

Best regards
Andreas

@webera1979
Copy link
Author

Hi Alex, can you maybe please have a look at my last question? Thank you so much, Andreas

@iamthesiz
Copy link
Collaborator

Yes will take a look asap

@webera1979
Copy link
Author

Thanks!

@CaveSeal
Copy link

CaveSeal commented Nov 18, 2020

@webera1979 Just curious, but are you accessing the headers using the Headers methods?

response.headers.get('Content-Type')

I've noticed while using a debugger before that the headers appear as an empty object literal.

https://developer.mozilla.org/en-US/docs/Web/API/Headers

@webera1979
Copy link
Author

webera1979 commented Nov 23, 2020

@CaveSeal : That is it! Thank you so much for your support. Reading the manuals makes sense from time to time.

The case I am driving is, that when the API-version changes, the SPA reloads softly on the next best occasion... for doing so, I need to inspect some header.

@LuoHuacheng
Copy link

I still have problem. I added some parameters in headers when I send requests, and I want to get these parameters in response, but the result is always null, can you take some time to help me look at this ? @alex-cory ,I use your codesandbox https://codesandbox.io/s/usefetch-provider-requestresponse-interceptors-s1lex?file=/src/index.js,I add Authorization in request inceptors and want to get it in response inceptors but does not work

import React from "react"
import { render } from "react-dom"
import { Snowflakes, Center } from "./components"
import useFetch, { Provider } from "use-http"
import { toCamel } from 'convert-keys'

import "./styles.css"

const TestUseFetch = () => {
	const { loading, error, data } = useFetch('/test.json', { data: [] }, []) // onMount (GET by default)
	console.log('data', data)
	return (
		<>
			<h2>onMount</h2>
			{error && error.messge}
			{loading && "Loading..."}
			{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
		</>
	)
}

const App = () => {
	const globalOptions = {
		interceptors: {
      request: ({ options }) => {
        options.headers = {
					Authorization: 'Bearer YOUR_AUTH_TOKEN'
				}
        return options
      },
      response: ({ response }) => {
				console.log('response.headers.Content-Type', response.headers.get('Content-Type'))
				console.log('response.headers.Authorization', response.headers.get('Authorization'))
				response.data = toCamel(response.data)
        return response 
      }
    }
	}
	return (
		<Provider options={globalOptions}>
			<Snowflakes>
				<Center>
					<TestUseFetch />
				</Center>
			</Snowflakes>
		</Provider>
	)
}

render(<App />, document.getElementById("root"))

@CaveSeal
Copy link

CaveSeal commented Dec 3, 2020

@LuoHuacheng If it's only the Authorization header that is null, then that is expected I think. The response would not usually contain the Authorization header, unless you explicitly add it on the server and use Access-Control-Expose-Headers: authorization to expose it.

@LuoHuacheng
Copy link

@LuoHuacheng If it's only the Authorization header that is null, then that is expected I think. The response would not usually contain the Authorization header, unless you explicitly add it on the server and use Access-Control-Expose-Headers: authorization to expose it.

@alex-cory No。I think that I did not make myself clear. What I want is that I can get options in request interceptors from the response, I don't want the headers or the Authorization or some others only, but I want to get all options I setted in request interceptor also. I use this in axios and it worked, I can get all this options through response.config, here is the code.

import axios from 'axios';

export const $http = axios.create({
  baseURL: 'baseUrl',
  headers: { 'Content-Type': 'application/json;charset=utf-8;' },
  notice: false, // show succeed msg automatically
  process: true, // process data in response interceptors
});

$http.interceptors.request.use(
  (config) => {
    config.headers['token'] = token;
    return config;
  },
  error => Promise.reject(error),
);

$http.interceptors.response.use(
  (response) => {
    const result = response.data;
    // process data
    if (response.config && !response.config.process) {
      return result;
    }
    // show succeed msg automatically
    if (response.config && response.config.notice && result.code === 0) {
      alert(result.msg);
      return;
    }
    // show failed msg
    if (result.code > 0) {
      alert(result.msg)
      return;
    }
    return result.data ? result.data : true;
  },
  (error) => {
    return Promise.reject(error.response.statusText);
  },
);

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants