Nest 实战 (二)
设置跨域
- main.ts 里面 写好了跨域规则
js
async function bootstrap() {
const app =
(await NestFactory.create) <
NestExpressApplication >
(AppModule,
{
cors: true, // 开启跨域访问
});
}
设置访问频率
安装
js
pnpm install express-rate-limit -S
使用
- main.ts 里面 写好了访问频率规则
js
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import rateLimit from "express-rate-limit";
// 配置文件
import { ConfigService } from "@nestjs/config";
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors: true, // 开启跨域访问
});
// 限制请求频率
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 1000, // 限制15分钟内最多只能访问1000次
})
);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
设置全局 API 访问前缀
设置
- (1) main.ts 里面 写好了 API 访问前缀
js
// 设置 api 访问前缀
const prefix = config.get < string > "app.prefix" || "";
app.setGlobalPrefix(prefix);
- (2) 配置文件
bash
# 开发环境配置
app:
prefix: 'v1'
port: 8080
logger:
# 项目日志存储路径,相对路径(相对本项目根目录)或绝对路径
dir: '../logs'
# 文件相关
file:
# 是否为本地文件服务或cos
isLocal: true
# location 文件上传后存储目录,相对路径(相对本项目根目录)或绝对路径
location: '../upload'
# 文件服务器地址,这是开发环境的配置 生产环境请自行配置成可访问域名
domain: 'http://localhost:8080'
# 文件虚拟路径, 必须以 / 开头, 如 http://localhost:8080/profile/****.jpg , 如果不需要则 设置 ''
serveRoot: '/profile'
# 文件大小限制,单位M
maxSize: 10
- (3) 调用
bash
http://localhost:3000/v1/test/config
全部
ts
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import rateLimit from "express-rate-limit";
// 配置文件
import { ConfigService } from "@nestjs/config";
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
cors: true, // 开启跨域访问
});
// 限制请求频率
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 1000, // 限制15分钟内最多只能访问1000次
})
);
// 设置 api 访问前缀
const prefix = config.get<string>("app.prefix") || "";
app.setGlobalPrefix(prefix);
await app.listen(process.env.PORT ?? 3000);
}
bootstrap();
调用
bash
http://localhost:3000/v1/test/config