96SEO 2026-08-15 10:00 0
使用者痛点:登录时需要自行查询数据库、比对密码并手动剔除敏感字段,代码易遗漏导致安全隐患。说起来,
// src/auth/auth.service.ts
import { Injectable。Logger,UnauthorizedException } from '@nestjs/common';import { JwtService } from '@nestjs/jwt';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { User } from 'src/user/entities/user.entity';import { removeUserData } from 'src/utils';@Injectable
export class AuthService {
private readonly logger = new Logger;constructor(
@InjectRepository
private readonly userRepository: Repository,private readonly jwtService: JwtService。) {}
// 验证账号密码
async validateUser: Promise {
const user = await this.userRepository.findOne({
再看where,{ account,isDeleted: false },});if )) {
delete user.passwordHash;delete user.isDeleted;return user,}
return null;}
// 生成 JWT
async createToken {
return this.jwtService.signAsync;}
// 登录成功后返回 token
async login {
const payload = {
account: user.account。userId: user.id,roleId: user.roleId,roleType: user.roleType,roleWeight: user.roleWeight,};其实,const token = await this.createToken;return { token };}
// 查询当前登录使用者信息
async queryCurrentUser {
try {
if {
const user = await this.userRepository.findOneBy;老实说,return removeUserData;}
} catch {
this.logger.error;throw new UnauthorizedException;}
}
}
使用者痛点:前端经常找不到统一的登录/登出接口,导致业务层自己实现重复逻辑。

import {
Controller。Post,Get,Body,BadRequestException,Req,Res,} from '@nestjs/common';import { ApiBody,ApiOperation,ApiResponse。ApiTags } from '@nestjs/swagger';import { AuthService } from './auth.service';import { LoginDto } from './dto/login.dto';@Controller
@ApiTags
export class AuthController {
constructor {}
@Post
@ApiOperation
@ApiBody
@ApiResponse
async login loginDto: LoginDto) {
const user = await this.authService.validateUser(
loginDto.account。loginDto.password,);if throw new BadRequestException;话说回来,try {
return await this.authService.login;} catch {
throw new BadRequestException;}
}
@Post
@ApiOperation
@ApiResponse
logout req,@Res res): void {
// 清除 cookie 中的 jwt
res.cookie });// 前端若存储在 localStorage,需要自行删除
res.status.send({
说到code。0,msg: 'success',result: { message: '登出成功' },});}
使用者痛点:缺少统一的请求参数校验,导致后端频繁出现参数缺失或格式错误的异常。其实,
import { ApiProperty } from '@nestjs/swagger';import { IsNotEmpty,IsString,IsEmail。Matches } from 'class-validator';export class LoginDto {
@IsEmail
@IsString
@IsNotEmpty
@ApiProperty({
description: '账号'。example: '',})
account!: string,@Matches.{8,16}$/,{
message:
'请输入8-16位数字+字母的密码'。})
@IsString
@IsNotEmpty
@ApiProperty
password!: string,}
使用者痛点:模块之间依赖混乱,常因忘记导入 TypeOrmModule 导致 Repository 为
import { Module } from '@nestjs/common';import { JwtModule } from '@nestjs/jwt';import { PassportModule } from '@nestjs/passport';import { TypeOrmModule } from '@nestjs/typeorm';import { AuthService } from './auth.service';话说回来,import { AuthController } from './auth.controller';import { JwtStrategy } from './jwt.strategy';import { JwtAuthGuard } from './jwt-auth.guard';import { User } from 'src/user/entities/user.entity';const jwtModule = JwtModule.register({
至于global,true。secret:'niunai',// 建议使用 env 配置更安全
signOptions:{ expiresIn:'24h' },});@Module({
imports:,controllers:,providers:,exports:。})
export class AuthModule {}
使用者痛点:token 验证逻辑散落各处,难以统一维护;忘记同步 secret 导致验证失败。
import { Injectable } from '@nestjs/common';import { PassportStrategy } from '@nestjs/passport';import { ExtractJwt,Strategy } from 'passport-jwt';@Injectable
export class JwtStrategy extends PassportStrategy {
constructor {
super({
jwtFromRequest : ExtractJwt.fromAuthHeaderAsBearerToken。ignoreExpiration : false,secretOrKey : 'niunai',// 与 JwtModule 注册时保持一致
});}
async validate{
return{
userId : payload.userId,account : payload.account。roleId : payload.roleId,roleType : payload.roleType,roleWeight : payload.roleWeight,};}
}
使用者痛点:每个受保护接口都要手动写 Guard,且排除路由时容易写错方法或忘记更新。
import {
Injectable,ExecutionContext。Logger,UnauthorizedException,} from '@nestjs/common';import { AuthGuard } from '@nestjs/passport';import { JwtService } from '@nestjs/jwt';import { excludedRoutes } from './excluded.routes';@Injectable
export class JwtAuthGuard extends AuthGuard {
private readonly logger = new Logger;constructor{
super;}
async canActivate:Promise{
const request = context.switchToHttp.getRequest;const{ path,method}=request;// 路由排除
const isExcluded = excludedRoutes.some(
route=> route.path===path && route.method===method);if return true;const token = request.get;this.logger.log;if{
throw new UnauthorizedException;
说起来,}
const = token.split;if{
throw new UnauthorizedException;}
try{
const decoded = await this.jwtService.verifyAsync;if{
request.user = decoded;return this.activate;}
}catch{
throw new UnauthorizedException;}
}
async activate:Promise{
return super.canActivate as Promise;}
}
排除路由示例
export const excludedRoutes =;说起来,
使用者痛点:忘记在入口文件挂载 Guard。导致未受保护的接口被外部直接访问。话说回来,
// main.ts
async function bootstrap{
const app = await NestFactory.create;app.useGlobalGuards);await app.listen;}
bootstrap,按理说,
User Pain Point: 前后端传输敏感数据时缺乏统一加解密方案。导致业务方自行实现且安全性参差不齐。
@IsString。@Length,@Matches等装饰器,并在全局开启 ValidationPipe,以防止 SQL 注入与 XSS。.validatePassword方法。
ts
import * as XLSX fro m ’xlsx’;import {@ njectable} fro m ’@ nestjs /common’;
@ Injectable export cl ass ExcelSe rvice{ /* Export JSON array to an excel file */ exportAsExcelFile:Buffer{ cons t worksheet:XLSX.WorkSheet= XLSX.utils.jsontosheet;cons t workbook:XLSX.WorkBook={Sheets:{data:wor kshee t},SheetNames:};retu rn XLSX.write;} } < / pre>
html
typescript
import{
Controller。Res,HttpStatus,Body,Post,BadRequestException,}from ’@nestjs/common’;话说回来,import{ExcelSe rvice}from ’./excel.service’;话说回来,import{ExcelDt o}from ’./dto/excel.dto’;import{ApiBody,ApiTags}from ’@nestjs/swagger’;
@Cont roller @ApiTags export cl ass ExcelCo ntroller{ con structor{} @Post @Ap iBody exp ortExcellbod y:E xcelDt o,@Resres ){ tr y{ con st buffer=this.excelSer vice.exportAsExcelFile;‑‑ set header‑‑- res.setHeader;res.setHeader}` );res.status.send;} ca tch{ thr ownew BadR equestExcept ion;} } }
typescript
// excel.module.ts
typescript
import{ Module}from ’@nestjs/common’;import{ExcelCon troller}from ’./excel.controller’;import{Ex ce lServic e}from ’./excel.service’;
@Module({ controllers:,providers:,exports:。}) expor t class Exce lM odule {}
typescript
// excel.dto.ts
typescript
import{ ApiProperty}from ’@nestjs/swagger’;import{ IsNotEmpty}from ’class-validator’;
export cla ss ExcelDt o{ ‑‑ file name —- ‑‑ api property —- ‑‑ is not empty —- ‑‑ …–- ,}
User Pain Point: 业务代码里经常出现 “创建人/更新人” 字段赋值还有 “删除敏感字段” 的重复实现,把这些通用操作抽离到 utils 可以明显提高代码可读性和维护性。
/**
* 通用工具函数集合
*/
import * as moment FROM ‘moment’;
// 设置创建者信息 export const setCreatedUser ==>{ const u=req?.user,table.createdBy=u?不过,.userId,table.createdByAccount=u?.account,table.updatedBy=u?老实说,.userId,怎么说呢,table.updatedByAccount=u?按理说,.account;return table;},
// 设置更新者信息 export const setUpdatedUser ==>{ const u=req?.user,说起来,table.updatedBy=u?.userId,table.updatedByAccount=u?.account,return table;},
// 移除非必要字段 export const removeUnnecessaryData ==>{ return data.map(item=>{ const obj={…item},老实说,obj.createdTime=item.createdTime?moment.format :'';obj.updatedTime=item.updatedTime?moment.format :'';delete obj.passwordHash;delete obj.isDeleted;return obj,});},
// 移除使用者实体中的内部字段,仅返回给前端必要信息
export const removeUserData ==>{
delete data.createdBy;delete data.createdByAccount;delete data.createdTime;delete data.updatedBy;说起来,delete data.updatedByAccount;说起来,delete data.updatedTime;delete d ata.passwordHash?,delete d ata.isDe le ted?,ret urn d ata?,};
作为专业的SEO优化服务提供商,我们致力于通过科学、系统的搜索引擎优化策略,帮助企业在百度、Google等搜索引擎中获得更高的排名和流量。我们的服务涵盖网站结构优化、内容优化、技术SEO和链接建设等多个维度。
| 服务项目 | 基础套餐 | 标准套餐 | 高级定制 |
|---|---|---|---|
| 关键词优化数量 | 10-20个核心词 | 30-50个核心词+长尾词 | 80-150个全方位覆盖 |
| 内容优化 | 基础页面优化 | 全站内容优化+每月5篇原创 | 个性化内容策略+每月15篇原创 |
| 技术SEO | 基本技术检查 | 全面技术优化+移动适配 | 深度技术重构+性能优化 |
| 外链建设 | 每月5-10条 | 每月20-30条高质量外链 | 每月50+条多渠道外链 |
| 数据报告 | 月度基础报告 | 双周详细报告+分析 | 每周深度报告+策略调整 |
| 效果保障 | 3-6个月见效 | 2-4个月见效 | 1-3个月快速见效 |
我们的SEO优化服务遵循科学严谨的流程,确保每一步都基于数据分析和行业最佳实践:
全面检测网站技术问题、内容质量、竞争对手情况,制定个性化优化方案。
基于用户搜索意图和商业目标,制定全面的关键词矩阵和布局策略。
解决网站技术问题,优化网站结构,提升页面速度和移动端体验。
创作高质量原创内容,优化现有页面,建立内容更新机制。
获取高质量外部链接,建立品牌在线影响力,提升网站权威度。
持续监控排名、流量和转化数据,根据效果调整优化策略。
基于我们服务的客户数据统计,平均优化效果如下:
我们坚信,真正的SEO优化不仅仅是追求排名,而是通过提供优质内容、优化用户体验、建立网站权威,最终实现可持续的业务增长。我们的目标是与客户建立长期合作关系,共同成长。
Demand feedback