Nestjs:无法放置,无法删除(404 未找到)
Nestjs: Cannot PUT, Cannot DELETE (404 not found)
我的任务是按照类似的 nestjs 示例为用户列表编写一个简单的 CRUD 程序。虽然 GET、POST 和 GET by id 工作正常,但 PUT 和 DELETE 不能正常工作。我得到 'User does not exist' 但是用户存在于数据库中。
控制器
@Controller('users')
export class UsersController {
constructor(private userService: UsersService) {}
.....
//Update a user's details
@Put('/update')
async updateUser(
@Res() res,
@Query('userid') userID,
@Body() createUserDto: CreateUserDto
) {
const user = await this.userService.updateUser(userID, createUserDto);
if (!user) throw new NotFoundException('User does not exist!');
return res.status(HttpStatus.OK).json({
message: 'User has been successfully updated',
user
})
}
//Delete a user
@ApiParam({ name: 'id' })
@Delete('/delete')
async deleteUser(@Res() res, @Query('userid') userID) {
const user = await this.userService.deleteUser(userID);
if (!user) throw new NotFoundException('Customer does not exist');
return res.status(HttpStatus.OK).json({
message: 'User has been deleted',
user
})
}
服务
// Edit user details
async updateUser(userID, createUserDto: CreateUserDto): Promise<User> {
const updatedUser = await this.userModel
.findByIdAndUpdate(userID, createUserDto, { new: true });
return updatedUser;
}
// Delete a customer
async deleteUser(userID): Promise<any> {
const deletedUser = await this.userModel
.findByIdAndRemove(userID);
return deletedUser;
}
我正在使用 swagger 来执行我的测试。我将 id 作为参数传递以查找和更新用户。
根据您的代码存储库,您没有使用 URL 参数,而是使用查询参数。两者的区别在于它们是如何传递给服务器的,以及它们是如何被告知服务器监听它们的。
查询参数
使用查询参数,您将它们传递给您的服务器,从 url 中的 ?
开始,然后使用 &
连接每个参数。一个示例可能类似于 http://localhost:3000?name=Test&id=a26408f3-69eb-4443-8af7-474b896a9e70
。请注意,有两个查询参数,一个名为 name
,一个名为 id
。在 Nest 中,要在路由处理程序中获取这些参数,您可以使用 @Query()
装饰器。示例 class 可能看起来像
@Controller()
export class AppController {
@Get()
getHello(@Query() query: { name: string, id: string }) {
return `Hello ${name}, your ID is ${id}`;
}
}
注意上面的url,调用的路由是基本路由(/
),添加了查询参数。
URL 参数
URL 参数是一种动态构建路由的方法,无需指定每个可能的路由 URL。这对于动态生成的 ID 之类的东西很有用。采取与上面类似的 URL,这次的样本 URL 可能看起来像 http://localhost:3000/Test/a26408f3-69eb-4443-8af7-474b896a9e70
。请注意这次没有 ?
或 &
,它看起来就像一个完整的 URL。要在嵌套中指定 URL 参数,您需要在资源声明装饰器中的参数名称之前加上一个冒号 (:
),以及必要的路径的任何其他部分。然后要访问 URL 参数,您需要在路由处理程序中使用 @Param()
装饰器,类似于 @Query()
装饰器。 class 示例为
@Controller()
export class AppController {
@Get(':name/:id')
getHello(@Param() params: { name: string, id: string })
return `Hello ${name}, your ID is ${id}`;
}
}
问题与解决方案
您当前正在调用 http://localhost/users/update/<ID>
就像您正在使用 URL 参数一样,但在您的路由处理程序中您期望 @Query()
获取 id。因此,没有找到 /users/update/:id
的处理程序,因此您在 return 中得到 404。您可以修改您的服务器以如上所述侦听 URL 参数,或者您可以修改 URL 以使用查询参数而不是 URL 参数发送请求。
我的任务是按照类似的 nestjs 示例为用户列表编写一个简单的 CRUD 程序。虽然 GET、POST 和 GET by id 工作正常,但 PUT 和 DELETE 不能正常工作。我得到 'User does not exist' 但是用户存在于数据库中。
控制器
@Controller('users')
export class UsersController {
constructor(private userService: UsersService) {}
.....
//Update a user's details
@Put('/update')
async updateUser(
@Res() res,
@Query('userid') userID,
@Body() createUserDto: CreateUserDto
) {
const user = await this.userService.updateUser(userID, createUserDto);
if (!user) throw new NotFoundException('User does not exist!');
return res.status(HttpStatus.OK).json({
message: 'User has been successfully updated',
user
})
}
//Delete a user
@ApiParam({ name: 'id' })
@Delete('/delete')
async deleteUser(@Res() res, @Query('userid') userID) {
const user = await this.userService.deleteUser(userID);
if (!user) throw new NotFoundException('Customer does not exist');
return res.status(HttpStatus.OK).json({
message: 'User has been deleted',
user
})
}
服务
// Edit user details
async updateUser(userID, createUserDto: CreateUserDto): Promise<User> {
const updatedUser = await this.userModel
.findByIdAndUpdate(userID, createUserDto, { new: true });
return updatedUser;
}
// Delete a customer
async deleteUser(userID): Promise<any> {
const deletedUser = await this.userModel
.findByIdAndRemove(userID);
return deletedUser;
}
我正在使用 swagger 来执行我的测试。我将 id 作为参数传递以查找和更新用户。
根据您的代码存储库,您没有使用 URL 参数,而是使用查询参数。两者的区别在于它们是如何传递给服务器的,以及它们是如何被告知服务器监听它们的。
查询参数
使用查询参数,您将它们传递给您的服务器,从 url 中的 ?
开始,然后使用 &
连接每个参数。一个示例可能类似于 http://localhost:3000?name=Test&id=a26408f3-69eb-4443-8af7-474b896a9e70
。请注意,有两个查询参数,一个名为 name
,一个名为 id
。在 Nest 中,要在路由处理程序中获取这些参数,您可以使用 @Query()
装饰器。示例 class 可能看起来像
@Controller()
export class AppController {
@Get()
getHello(@Query() query: { name: string, id: string }) {
return `Hello ${name}, your ID is ${id}`;
}
}
注意上面的url,调用的路由是基本路由(/
),添加了查询参数。
URL 参数
URL 参数是一种动态构建路由的方法,无需指定每个可能的路由 URL。这对于动态生成的 ID 之类的东西很有用。采取与上面类似的 URL,这次的样本 URL 可能看起来像 http://localhost:3000/Test/a26408f3-69eb-4443-8af7-474b896a9e70
。请注意这次没有 ?
或 &
,它看起来就像一个完整的 URL。要在嵌套中指定 URL 参数,您需要在资源声明装饰器中的参数名称之前加上一个冒号 (:
),以及必要的路径的任何其他部分。然后要访问 URL 参数,您需要在路由处理程序中使用 @Param()
装饰器,类似于 @Query()
装饰器。 class 示例为
@Controller()
export class AppController {
@Get(':name/:id')
getHello(@Param() params: { name: string, id: string })
return `Hello ${name}, your ID is ${id}`;
}
}
问题与解决方案
您当前正在调用 http://localhost/users/update/<ID>
就像您正在使用 URL 参数一样,但在您的路由处理程序中您期望 @Query()
获取 id。因此,没有找到 /users/update/:id
的处理程序,因此您在 return 中得到 404。您可以修改您的服务器以如上所述侦听 URL 参数,或者您可以修改 URL 以使用查询参数而不是 URL 参数发送请求。