Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.
like image 423
infodev Avatar asked Oct 24 '18 15:10

infodev


2 Answers

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 });
like image 114
Martin Adámek Avatar answered Oct 07 '22 14:10

Martin Adámek


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

 @Get()
    findHeaderexample(@Res() res,@Req req) {
        return req.headers;
}
like image 3
Riadh farhati Avatar answered Oct 07 '22 15:10

Riadh farhati