【发布时间】:2020-12-24 19:52:46
【问题描述】:
当我执行以下代码时,我从服务器收到“201 Created”响应,但实际上数据并未插入服务器。
我在我的应用程序中使用带有 TypeORM 和 Postgres 的 nestJS。
import { Repository, EntityRepository } from "typeorm";
import { User } from './user.entity';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { ConflictException, InternalServerErrorException } from "@nestjs/common";
@EntityRepository(User)
export class UserRepository extends Repository<User>{
async signUp(authCredentialsDto: AuthCredentialsDto): Promise<void>{
const {username, password} = authCredentialsDto;
const user = new User();
user.username = username;
user.password = password;
try{
await user.save();
} catch (error) {
if (error.code === '23505'){ // error code for duplicate value in a col of the server
throw new ConflictException('Username already exists');
} else {
throw new InternalServerErrorException();
}
}
}
}
我在 VS Code 终端中得到以下响应,而不是从服务器获得“201 Crated”:
(node:14691) UnhandledPromiseRejectionWarning: Error: Username already exists
at UserRepository.signUp (/home/rajib/practicing coding/nestJS-projects/nestjs-task-management/dist/auth/user.repository.js:24:23)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:14691) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:14691) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
控制器模块代码如下:
import { Controller, Post, Body, ValidationPipe } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
@Controller('auth')
export class AuthController {
constructor( private authService: AuthService){}
@Post('/signup')
signUp(@Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto): Promise<void>{
return this.authService.signUp(authCredentialsDto);
}
}
【问题讨论】:
-
您的代码中是否有没有
await回复的地方?还是您使用res.send()而不是从controller返回值? -
你能添加你的控制器代码吗?
-
@JayMcDoniel 感谢您的回复。如果可以帮助您解决我的问题,我已经编辑了帖子并在我的帖子中添加了 controller 代码。
-
@yash 感谢您的回复。如果可以帮助您解决我的问题,我已经编辑了帖子并在我的帖子中添加了 controller 代码。
标签: javascript node.js nestjs