I am trying to integrate device-detector npm module in my application in order to detect the browser details. For that I am using this module npm i device-detector-js
I have integrated as it is code snippet in my code.
Below is my code:
app.controller.ts
import { Controller, Get, Req } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(@Req() req): string {
console.log(req.headers);
return this.appService.getHello();
}
}
app.service.ts
import { Inject, Injectable } from '@nestjs/common';
import DeviceDetector = require("device-detector-js");
@Injectable()
export class AppService {
private readonly deviceDetector = new DeviceDetector();
getHello(): string {
const userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.81(Windows; Intel windows 8_8.1_10_11) Safari/537.36";
const result = this.deviceDetector.parse(userAgent);
console.log(JSON.stringify(result));
return 'Hello World!';
}
}
Output
[Nest] 23300 - 12/04/2022, 1:26:55 pm LOG [RouterExplorer] Mapped {/test, GET} route +2ms
[Nest] 23300 - 12/04/2022, 1:26:55 pm LOG [NestApplication] Nest application successfully started +4ms
{
host: 'localhost:3000',
connection: 'keep-alive',
'cache-control': 'max-age=0',
'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google
Chrome";v="98"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
dnt: '1',
'upgrade-insecure-requests': '1',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36'
}
It's working but not giving correct info as I am using Windows but it's showing Macintosh. Why is this happening?
Just pass headers from controller into service, something like this: