Skip to content

Refactored axios headers helpers to the AxiosHeaders class;#4753

Closed
DigitalBrainJS wants to merge 7 commits intoaxios:mainfrom
DigitalBrainJS:feat/AxiosHeaders
Closed

Refactored axios headers helpers to the AxiosHeaders class;#4753
DigitalBrainJS wants to merge 7 commits intoaxios:mainfrom
DigitalBrainJS:feat/AxiosHeaders

Conversation

@DigitalBrainJS
Copy link
Collaborator

@DigitalBrainJS DigitalBrainJS commented May 28, 2022

  • Added AxiosHeaders class;
  • minor dev environment improvements;
  • Refactored transformData helper;
  • Refactored dispatchRequest
  • Updated TS typings;

Now the headers object has Map-like methods:

  • set
  • get
  • has
  • delete
  • clear

Using these methods guarantees caseless work with headers. The original header case will be preserved.
At the same time, the headers can still be manipulated directly - they will be normalized after each iteration of the data transformation.
The 'Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent' headers have accessors:

  • setContentType(value, [rewrite])
  • getContentType([parser/matcher])
  • hasContentType([matcher])
const {transformRequest, transformResponse}= axios.defaults;

await axios.post('https://httpbin.org/post', {}, {
  transformRequest: [transformRequest[0], (data, headers)=> {
    headers.setUserAgent('Mozilla/3.0 (X11; I; AIX 2)');
    console.log('My header', headers.get('my-header'));
  }],
  transformResponse: [transformResponse[0], (data, headers)=> {
    console.log(headers);
    console.log('Content Length (direct access):', headers['content-length']);
    console.log('Content Length:', headers.getContentLength());
    console.log('Has server header:', headers.has('sErvEr'));
    console.log('Is gunicorn server:', headers.has('server', 'gunicorn'))
    console.log('Gunicorn version:', headers.get('server', /gunicorn\/([\d.]+)/)[1])
  }],
  headers: {
    'my-header': 'value1'
  }
});

Output:

My header value1
AxiosHeaders {
  date: 'Sat, 28 May 2022 14:26:23 GMT',
  'content-type': 'application/json',
  'content-length': '463',
  connection: 'close',
  server: 'gunicorn/19.9.0',
  'access-control-allow-origin': '*',
  'access-control-allow-credentials': 'true',
  [Symbol(defaults)]: null
}
Content Length (direct access): 463
Content Length: 463
Has server header: true
Is gunicorn server: true
Gunicorn version: 19.9.0

@DigitalBrainJS DigitalBrainJS changed the title Refactored axios headers helpers to the AxiosHeader class; Refactored axios headers helpers to the AxiosHeaders class; May 28, 2022
@DigitalBrainJS DigitalBrainJS marked this pull request as draft June 6, 2022 22:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants