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

问题描述 投票:0回答:2

我正在尝试将设备检测器 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,但它显示的是 Macintosh。为什么会出现这种情况?

node.js nestjs device-detection
2个回答
5
投票

只需将标头从控制器传递到服务中,如下所示:

// 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!';
}

0
投票

似乎

user-agent
属性并不总是可用。

我发现这个使用参数装饰器的小技巧,它可能会有所帮助:

export const UserAgent = createParamDecorator(
  (data: unknown, ctx: ExecutionContext): string => {
    const request = ctx.switchToHttp().getRequest();
    return request.headers['user-agent'];
  },
);

// in your controller :
getHello(@UserAgent() userAgent: string): string {
  console.log(userAgent);
  return this.appService.getHello({'user-agent': userAgent});
}
© www.soinside.com 2019 - 2024. All rights reserved.