如何在NestJs/NodeJs中检测浏览器详细信息



我正在尝试在我的应用程序中集成设备检测器npm模块,以检测浏览器的详细信息。为此,我使用此模块npm i device-detector-js

我已经在代码中集成了代码片段。

以下是我的代码:

应用程序控制器.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!';
}
}

输出

[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'
}

它工作,但没有提供正确的信息,因为我使用的是Windows,但它显示的是Macintosh。为什么会发生这种情况?

只需将头从控制器传递到服务中,类似于以下内容:

// controller
getHello(@Req() req): string {
console.log(req.headers);
return this.appService.getHello(req.headers);
}
// service
getHello(headers: {'user-agent': string }): string {
const userAgent = headers['user-agent']; 
const result = this.deviceDetector.parse(userAgent);
console.log(JSON.stringify(result));
return 'Hello World!';
}

相关内容

最新更新