0
votes

I used a simple statement like below to access headers in loopback4.

console.log(request.headers);

But it is printing undefined. A sample request headers that I want to access is in the image. request header image

I am receiving the request and its headers which is perfectly fine. It's just that I am not able to access its headers as I am getting undefined from request.headers.

I am a beginner in loopback so pls explain it.

If i have to use a bodyparser then how i would have to use it in loopback4 because it is different from express.

3

3 Answers

1
votes

Update

The original answer, although valid, is not the recommended way. Use dependency injection instead:

import {inject} from '@loopback/core';
import {get, param} from '@loopback/rest';

export class SomethingController {
  constructor() {}

  @get('/something')
  something(@param.header.string('x-your-header') yourHeader: string): void {
    // Use your header.
    // e.g. Log to console
    console.log(yourHeader);
  }
}

Unlike the REQUEST object, this strips away unnecessary info and provides built-in coercion.

Further reading


Original answer

If you're attempting to access the headers in a Controller, then you can inject the REQUEST object:

import {inject} from '@loopback/core';
import {get, Request, RestBindings} from '@loopback/rest';

export class SomethingController {
  constructor(@inject(RestBindings.Http.REQUEST) private req: Request) {}

  @get('/something')
  something(): void {
    // Get the headers
    this.req.headers;
  }
}
0
votes

You can also use Context, example

import {inject} from '@loopback/core';
import {
  post, RequestContext
} from '@loopback/rest';

export class UserController {
  constructor(
    @inject.context() 
    public context: RequestContext,
  ) {}

    @post('/users/logout', {
    responses: {
      '200': {
        description: 'Return success',
        content: {
          'application/json': {
            schema: {
              type: 'object'               
            },
          },
        },
      },
    },
  })
     async logout(): Promise<object> {
    // ensure the token exists
    const authHeader = this.context.request.headers.authorization;
    if(authHeader && authHeader.split(" ")[1]){
      //    remove token
      return {code:204, status: true, message:'Logout successful'};
    }else{
      return {code: 404, status: false, message:'Something went wrong'};
    }    
  }
}
-1
votes

In sequence.ts, request object is called via context.

  const {request, response} = context;
  console.log(request.headers)

add log in sequence.ts to get the request headers.