【发布时间】:2022-10-31 07:30:38
【问题描述】:
我正在尝试在我的应用程序中集成设备检测器 npm 模块以检测浏览器详细信息。为此我正在使用这个模块npm i device-detector-js
我已经在我的代码中集成了代码 sn-p。
下面是我的代码:
应用程序控制器.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();
}
}
应用服务.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。为什么会这样?
【问题讨论】:
-
这是因为您对用户代理进行了硬编码:))) 您应该以某种方式从请求中获取用户代理并将其传递给
deviceDetector -
您需要传递请求的用户代理标头。如果您只是传递包含
Macintosh的相同字符串,它将始终给出相同的结果... -
我如何通过请求传递它,请您解释一下或给我看一些代码。
-
@Kuzzy 我已经更新了我的帖子,你可以看看吗
标签: node.js nestjs device-detection