【问题标题】:Unable to send POST requests from an Ionic app to a NestJS backend无法将 POST 请求从 Ionic 应用程序发送到 NestJS 后端
【发布时间】:2020-07-08 01:26:39
【问题描述】:

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

对象 {headers: {…}, status: 500, statusText: "Internal Server 错误”,网址:“http://localhost:3000/api/users”,确定:假, 名称:“HttpErrorResponse”,消息:“http://localhost:3000/api/users 的 Http 失败响应:500 内部服务器错误”,错误: {…}} home.page.ts: 36: 14

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

[Nest] 18696 - 03/27/2020, 10:39:04 AM [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;
}

CORS 在我的 NestJS 后端也被激活。此外,有趣的是 GET 请求(通过 Ionic 以及通过 Postman 或直接输入到浏览器)工作。如果我通过 Postman 发出 POST 请求或直接将它们输入到浏览器中,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) 并只输入 credentials 而没有 JSON.stringify() 时,请求没有发送也很有趣。

我在这里做错了什么?

【问题讨论】:

  • 可能选择了错误的httpclient.post 过载。尝试直接将内容类型指定为 json 并尝试在没有JSON.stringify() 的情况下使其工作。它应该在没有JSON.stringify() 的情况下工作! this.http.post('http://localhost:3000/api/users', credentials, { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
  • 不行,还是不行。正文不会传递到我的后端,如果没有 JSON.stringify() 方法,请求将无法工作。 HttpClient 是从“@angular/common/http”导入的。我还添加了你建议的标题..
  • 请求怎么不能发送?您是否收到有关预检 OPTIONS 请求的 CORS 错误?
  • 不,我只是收到问题中列出的错误。如果我将正文记录在我的 NestJS 控制器中,例如 console.log('body', createUserDto);它说:body CreateUserDto {}。下面是上面列出的错误。所以我发送到控制器的身体是空的,但在浏览器的网络选项卡中,身体是存在的。另外,如果我将其登录到我的 ionic 应用程序中。

标签: angular typescript ionic-framework rxjs nestjs


【解决方案1】:

如果您的“凭证”是一个具有正确接口的对象,那么只需按原样发送它,而无需 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”。

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

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

【讨论】:

  • 感谢您的回答。 “凭证”是一个使用正确接口的对象,但如果我在没有 JSON.stringify() 的情况下使用或发送它,则请求不会发送到后端。使用 JSON.stringify() 请求到达后端。正如我在我的问题中提到的:使用 Postman 或通过在浏览器中输入端点 url 一切正常。 “pluck”到底在做什么?真的需要吗?
  • 当您使用 http.post(URL, body) 发出请求时,正文将在发送到您的后端时被转换为有效的 Json,因此无需转换为 Json你。查看更多信息 [单击此处] (angular.io/guide/http#making-a-post-request)。你是对的,pluck 不是必需的,是一个可选的操作符,可以从 API 响应中获取用户。
  • 好的,但正如我之前提到的。如果我删除 stringify 方法,则不会发送请求,并且浏览器开发工具的网络分流器中没有任何反应。
猜你喜欢
  • 2015-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
  • 2021-08-31
  • 1970-01-01
  • 2014-02-19
  • 2020-05-23
相关资源
最近更新 更多