Skip to content

Nest 实战 (四)

Nest 使用 端口 和 获取真实 IP

获取真实 IP

安装

bash
pnpm install request-ip -S

全局使用

  • main.ts 中使用绑定到请求信息中 ip 字段
ts
// 获取真实 ip 存储到用户请求信息中得IP字段
app.use(requestIpMw({ attributeName: "ip" }));

改变端口

  • main.ts 中使用 app.listen 方法中的 port 参数
ts
//服务端口
const port = config.get<number>("app.port") || 8080;
await app.listen(port);

全部代码

ts
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import rateLimit from "express-rate-limit";
// 配置文件
import { ConfigService } from "@nestjs/config";
// 静态
import { join } from "path";
import { NestExpressApplication } from "@nestjs/platform-express";

// 全局验证器
import { ValidationPipe } from "@nestjs/common";
// 全局过滤器
import { HttpExceptionsFilter } from "src/common/filters/http-exceptions-filter";

// 获取真实IP
import { mw as requestIpMw } from "request-ip";
async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    cors: true, // 开启跨域访问
  });

  // 限制请求频率
  app.use(
    rateLimit({
      windowMs: 15 * 60 * 1000, // 15分钟
      max: 1000, // 限制15分钟内最多只能访问1000次
    })
  );

  // 获取配置文件
  const config = app.get(ConfigService);
  console.log(config);
  // 设置 api 访问前缀
  const prefix = config.get<string>("app.prefix") || "";
  app.setGlobalPrefix(prefix);

  // 设置静态资源路径
  const rootPath = process.cwd();
  const baseDirPath = join(rootPath, config.get("app.file.location") || "");
  console.log(baseDirPath);
  app.useStaticAssets(baseDirPath, {
    prefix: "/profile/", // 虚拟路径
    maxAge: 86400000 * 365, // 过期时间 我设置成1年
  });

  // 开启全局管道
  app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true }));
  // 开启全局过滤器
  app.useGlobalFilters(new HttpExceptionsFilter());

  // 获取真实 ip
  app.use(requestIpMw({ attributeName: "ip" }));

  //服务端口
  const port = config.get<number>("app.port") || 8080;
  await app.listen(port);
}
bootstrap();