我试图在我的应用程序中集成设备检测器npm模块,以检测浏览器的细节。为此,我使用了这个模块npm i device-detector-js
我已经在我的代码中集成了代码片段。
下面是我的代码:
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!';
}
}输出
[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,但它显示的麦金塔。为什么会发生这种情况?
发布于 2022-04-12 08:08:08
只需将头从控制器传递到服务,如下所示:
// 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!';
}https://stackoverflow.com/questions/71838572
复制相似问题