"generateOptions": {
"spec": false
}
创建模型 nest g m xx
创建服务 nest g s xx
创建处理 nest g c xx
app.module.ts:全局注入入口
import { UserModule } from './user/user.module';
import { Profile } from './profile/profile.entity';
@Module({
imports: [
ArticleModule,
UserModule,
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'root',
database: 'nestjs_test',
entities: [Article, Content, Label, User, Profile],
synchronize: true,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
上面代码配置了数据库还有entities、controller
数据库连接需要用到的包:"@nestjs/typeorm": "^11.0.0","mysql2": "^3.14.1",等等
user为例子
JWT
import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
const JWT_SECRET = 'wttoken_yxy';// 建议放到 .env
const IS_DEV_MODE = true; // 开发环境标志
@Injectable()
export class JwtAuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
const request = context.switchToHttp().getRequest();
const auth = request.headers['authorization'];
if (!auth || !auth.startsWith('Bearer ')) {
throw new UnauthorizedException('未登录或token无效');
}
const token = auth.replace('Bearer ', '');
try {
// 尝试验证token
const payload = jwt.verify(token, JWT_SECRET);
request.user = payload;
return true;
} catch (error) {
// 开发环境下,如果token验证失败,使用固定的测试用户信息
if (IS_DEV_MODE) {
console.warn('开发环境: JWT验证失败,使用测试用户身份');
request.user = {
userId: 1,
username: 'testuser'
};
return true;
}
throw new UnauthorizedException('token无效或已过期');
}
}
}
请求所有用户(查询)
// 用户管理API - 需要JWT认证
@UseGuards(JwtAuthGuard)
@Get('users')
findAll() {
return this.userService.findAll();
}
需要标记这是controller层