infodev
infodev

Reputation: 5235

Add headers HttpRequest in NestJS

I'm trying to make a Http request in NestJS

As it's inspired from angular I jave append my Headers

import { Injectable, HttpService} from '@nestjs/common';
...
const headersRequest = new Headers();
headersRequest.append('Content-Type', 'application/json');
headersRequest.append('Authorization', `Basic ${encodeToken}`);

Then call the api

const result = await this.httpService.post(apiUrl, newDevice, { headers: headersRequest });

I get an error

ReferenceError: Headers is not defined

And when I ass Headers to import I get this message waring in VScode

Only a void function can be called with the 'new' keyword.

Upvotes: 18

Views: 57788

Answers (6)

Bruno Minuk
Bruno Minuk

Reputation: 193

You also can change it with axios interceptor:

this.httpService.axiosRef.interceptors.request.use(function (config) {
      config.headers.Authorization = `Basic ${encodeToken}`;
      return config;
    });

Upvotes: 4

Andrew Zagarichuk
Andrew Zagarichuk

Reputation: 509

You could use withCredentials option as below:

export const HttpMessagingProvider = HttpModule.registerAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    baseURL: configService.get('vendors.apiEndpoint'),
    timeout: 5000,
    maxRedirects: 5,
    withCredentials: true,
  }),
  inject: [ConfigService]
});

Upvotes: 0

Pasindu Jayasinghe
Pasindu Jayasinghe

Reputation: 101

If you want to set a custom header, you can use @ApiHeader()

@ApiHeader({
  name: 'api-key',
  description: 'api-key',
})

Upvotes: 1

Lee Alexis
Lee Alexis

Reputation: 61

Another option (since nest v5 introduced HttpModule.registerAsync) if your encodeToken is pretty static or hardcoded from your config is setting it up in the module level:

import { Module, HttpModule } from '@nestjs/common';
import { ConfigModule } from '..';
import { ConfigService } from '../config/config.service';


@Module({
  imports: [
    ConfigModule,
    HttpModule.registerAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        baseURL: configService.get('vendors.apiEndpoint'),
        headers: {          
          'Authorization': 'Basic ' + configService.get('vendors.encodeToken')
        },
        timeout: 7000,
        maxRedirects: 5
      }),
      inject: [ConfigService]
    })
  ],
  // ... other module stuff
})

export class MyModule {}

Upvotes: 6

Martin Adámek
Martin Adámek

Reputation: 18399

NestJS uses axios under the hood to make http requests, take a look at its documentation for request configuration:

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

Looks like there is no interface for headers, just pass a plain JS dictionary object:

const headersRequest = {
    'Content-Type': 'application/json', // afaik this one is not needed
    'Authorization': `Basic ${encodeToken}`,
};

const result = await this.httpService.post(apiUrl, newDevice, { headers: headersRequest });

Upvotes: 33

Riadh farhati
Riadh farhati

Reputation: 104

I think this method false in for read headers parameter just req.headers example

 @Get()
    findHeaderexample(@Res() res,@Req req) {
        return req.headers;
}

Upvotes: 4

Related Questions