coding_kills_me
coding_kills_me

Reputation: 74

How to get headers from AxiosResponse-Observable?

Using NestJS, Axios returns an Observable<AxiosResponse>.

How can I get the headers of a GET- or HEAD-Request?

Lets say I make a HEAD-request:

import { HttpService } from '@nestjs/axios';

const observable = this.httpService.head(uri);

How can I get the headers from the result?


Update:

I found a nice workaround that just works with a single line of code.

There is another library called https with is more powerful:

import http from "https";

await http.request(uri, { method: 'HEAD' }, (res) => {
  console.log(res.headers);
}).on('error', (err) => {
  console.error(err);
}).end();

Upvotes: 3

Views: 693

Answers (2)

Andrey Bessonov
Andrey Bessonov

Reputation: 348

According to https://github.com/axios/axios#request-config:

For request headers you should use something like this:

this.httpService.axiosRef.interceptors.request.use(function (config) {
    // Do something before request is sent
console.log(config);
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

You should use it onModuleInit (to prevent working a few interceptors in a time)

Also you can make own module like in this answer: https://stackoverflow.com/a/72543771/4546382

For the response headers you can just use response.headers

Upvotes: 0

Tobias S.
Tobias S.

Reputation: 23825

The headers of the response are available in the subscribe callback with the headers property.

this.httpService.head(uri).subscribe(res => {
    console.log(res.headers)
});

Playground

Upvotes: 3

Related Questions