首页 > 解决方案 > 无法将 POST 请求从 Ionic 应用程序发送到 NestJS 后端

问题描述

我设置了一个简单的 Ionic 5 应用程序和一个 NestJS 后端。现在我想从我的应用程序向我的后端发送一个 POST 请求,但我总是在浏览器控制台中收到以下错误消息:

对象 {headers: {...}, status: 500, statusText: "Internal Server Error", url: " http://localhost:3000/api/users ", ok: false, name: "HttpErrorResponse", message: "Http http://localhost:3000/api/users的失败响应:500 Internal Server Error ", error: {…}} home.page.ts: 36: 14

在我的 NestJS 后端中,我收到以下错误消息:

[Nest] 18696 - 2020 年 3 月 27 日,上午 10:39:04 [ExceptionsHandler] 用户验证失败:密码:需要路径password。,用户名:路径username是必需的。,电子邮件:路径email是必需的。+ 43794 毫秒

在浏览器的网络选项卡中,我收到状态代码为 500 的错误(内部服务器错误):

Request URL: http://localhost:3000/api/users
Request method: POST
Remote address: 127.0.0.1: 3000
Status code:
500
Version: HTTP / 1.1
Referrer Policy: no-referrer-when-downgrade

所需的参数也正确发送:

{"email":"test@test.de","username":"testname","password":"testpassword"}

我的 POST 请求的控制器结构如下:

@Controller('/users')
export class UsersController {
    constructor(private usersService: UsersService) { }

    // POST request containing the data required to create a new user
    @Post()
    async createUser(@Res() res, @Body() createUserDto: CreateUserDto) {
        console.log('body', createUserDto);

        const user = await this.usersService.create(createUserDto);
        if (!user) throw new InternalServerErrorException('User could not be created!');
        return res.status(HttpStatus.OK).json({
            message: "User has been created successfully",
            user
        })
    }
...

使用的 DTO 如下所示:

export class CreateUserDto {
    readonly email: string;
    readonly username: string;
    readonly password: string;
}

我的 NestJS 后端也激活了 CORS。此外,有趣的是 GET 请求(通过 Ionic 以及通过 Postman 或直接输入到浏览器)工作。如果我通过 Postman 发出请求或直接将它们输入到浏览器中,POST 请求也可以工作。

我在 Ionic 应用程序中以这种方式测试 POST 请求:

  ngOnInit() {
    this.createAccount(this.createUserDto).subscribe((res) => {
      console.log('Request send', res);
    }, (err) => {
      console.log('Failed', err);

    });
  }

  createAccount(credentials): Observable<any> {
    return this.http.post('http://localhost:3000/api/users', JSON.stringify(credentials));
  }

有趣的是,当我删除JSON.stringify(credentials)并只输入没有 JSON.stringify() 的凭据时,请求没有发送。

我在这里做错了什么?

标签: angulartypescriptionic-frameworkrxjsnestjs

解决方案


如果您的“凭证”是具有正确接口的对象,那么只需按原样发送它,而无需 JSON.stringify() 它。

我假设凭证有这样的东西:

const credentials = {
    email: 'foo@bar.biz',
    username: 'username',
    password: 'some_password',
}

然后对您的 observable 进行一些更改以获取用户数据并正确捕获错误:

 createAccount(credentials): Observable<any> {
    return this.http.post('http://localhost:3000/api/users', credentials)
        .pipe(
           pluck('user'),
           catchError(err => {
            return throwError(err);
           })
        )
  }

确保导入 rxjs 运算符“pluck”和“catchError”以及可观察的“throwError”。

有关这些运算符的更多信息:

我希望它对你有用!祝你好运!


推荐阅读