资料库
后端开发
NestJS
NestJS

如何获取用户 ip

import { Request } from 'express';
import { Controller, Get, Req } from '@nestjs/common';
 
@Controller('example')
export class ExampleController {
  @Get('ip')
  getIpAddress(@Req() request: Request): string {
    const ipAddress = request.ip;
    return `Your IP address is: ${ipAddress}`;
  }
}

jest, ts-jest 版本问题导致的报错

  1. SyntaxError: /Users/xxxx/app.service.spec.ts Missing initializer in const declaration. (8:16)

  2. TypeError: Jest: a transform must export something

  3. SyntaxError: Cannot use import statement outside a module

解决办法

使用固定版本号,可以用这个

"ts-jest": "29.0.3",
"jest": "29.3.1",

或者初始化一个新的 nestjs 项目,看其中的版本号是什么,拷贝过来

npm i -g @nestjs/cli
nest new project-name

上面的方式如果解决不了的话,尝试

rm -rf node_modules
npm install --save-dev jest@latest ts-jest@latest

https://docs.nestjs.com/first-steps (opens in a new tab)