You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS注册/登录返回空JWT Token问题求助

问题:用户注册/登录时返回空Token

核心问题定位

你的AuthController中,login和registration方法仅调用了服务层逻辑,但没有返回任何数据,这是接口返回空的直接原因。

修复步骤

1. 修正Controller的返回逻辑

修改AuthController中的两个方法,将服务层的处理结果返回:

import {
  Body,
  Controller,
  Post,
  UsePipes,
  ValidationPipe,
} from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { CreateUserDto } from '../users/dto/create-user.dto';
import { AuthService } from './auth.service';

@ApiTags('Авторизация')
@Controller('auth')
export class AuthController {
  constructor(private authService: AuthService) {}

  @UsePipes(new ValidationPipe())
  @Post('/login')
  async login(@Body() userDto: CreateUserDto) {
    return await this.authService.login(userDto);
  }

  @UsePipes(new ValidationPipe())
  @Post('/registration')
  async registration(@Body() userDto: CreateUserDto) {
    return await this.authService.registration(userDto);
  }
}

2. 优化JwtStrategy的配置方式

避免直接读取process.env,改用注入的ConfigService获取密钥,保持配置一致性:

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { User } from '../../users/users.model';
import { UsersService } from '../../users/users.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService,
    private readonly usersService: UsersService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: configService.get('SECRET_KEY'),
    });
  }

  async validate(user: User) {
    return await this.usersService.getUserById(user.id);
  }
}

3. 清理注册逻辑的冗余操作(可选)

检查UsersService的createUser方法,如果该方法已经完成用户保存到数据库的操作,可移除registration中的冗余save()调用:

async registration(userDto: CreateUserDto) {
  const candidate = await this.userService.getUserByEmail(userDto.email);
  if (candidate) {
    throw new HttpException(
      'Пользователь с таким email уже существует',
      HttpStatus.BAD_REQUEST,
    );
  }
  const hashPassword = await bcrypt.hash(userDto.password, 6);
  const user = await this.userService.createUser({
    ...userDto,
    password: hashPassword,
  });
  const tokens = await this.issueTokenPair(user);
  return { user: this.returnUserFields(user), ...tokens };
}

验证修复效果

修改完成后重启服务,再次调用注册/登录接口,即可正常返回包含user、accessToken和refreshToken的JSON数据。

内容的提问来源于stack exchange,提问作者Deemoonn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 15:13:43