首页 > 解决方案 > 为什么我的 POST 数据没有在 Ionic 4 中正确提交?

问题描述

我正在将我的 Ionic 应用程序升级到版本 4,并且遇到了一个奇怪的问题,我不确定数据是否正确提交到我的 API。

我已将其精简到尽可能基本的程度,API 仍然返回 401 Unauthorized 错误。

我知道 API 有效,因为当我通过 Postman 提交相同的内容时,我会收到预期的数据......

我正在导入HttpClient...

import { HttpClient, HttpHeaders } from '@angular/common/http';

这是我的精简功能,它在单击提交按钮时运行。

onSubmit() {

    const headers = new HttpHeaders({
        'Content-Type': 'application/x-www-form-urlencoded'
    });

    let body = {
        'username': 'test',
        'password': 'test',
    }

    this.http
        .post(this.apiService.url, body, { headers: headers })
        .subscribe((data: any) => {
            console.log(data);
        }, error => {
            console.log('error');
        });
}

这一切都在 Ionic 3 中完美运行,所以我真的很困惑为什么它现在不起作用。

标签: angularionic-framework

解决方案


这篇文章为我解决了这个问题。显然 Angular 5+ 会为您处理标题,所以我所要做的就是删除它们并且它起作用了。

onSubmit() {

    let body = {
        'username': 'test',
        'password': 'test',
    }

    this.http
        .post(this.apiService.url, body)
        .subscribe((data: any) => {
            console.log(data);
        }, error => {
            console.log('error');
        });
}

https://stackoverflow.com/a/47560146/10646827


推荐阅读