首页 > 解决方案 > Ionic-native HTTP POST 方法在 iOS 上不起作用(但在 Android 上完美运行)

问题描述

我在我的 Ionic 4 项目中使用 @ionic-native/http 通过 POST 方法发送带有 UserId 和 Password 的正文和带有 'Content-Type': 'application/json' 的标头来登录用户。它在 android 中运行良好,但在 iOS 上它以 http 400 错误响应。

Dependencies: 

"@ionic-native/http": "^5.3.0",

"cordova-plugin-advanced-http": "^2.0.9",

我厌倦了使用@angular/http,但它在浏览器、android 和 iOS 上给出了 CORS 错误。而且我无法更改服务器端代码以启用 CORS。

代码:

import { HTTP } from '@ionic-native/http/ngx';

// Login method  
async login(userId, password) {
    // login user
    const httpBody = {
      'UserId': userId,
      'Password': btoa(password)
    };
    const httpHeader = {
      'Content-Type':  'application/json',
    };
    const user = await this.http.post(this.loginURL, httpBody, httpHeader);
    return JSON.parse(user.data);
  }

StatusCode 200 的预期结果响应

StatusCode 400 的实际结果响应

标签: ionic4ionic-nativecordova-plugin-advanced-http

解决方案


我有同样的问题;就我而言,我通过将数据序列化程序设置为“utf8”并将 Content-Type 标头设置为“application/x-www-form-urlencoded”来修复它

this.http.setDataSerializer('utf8');
const httpHeader = {
  'Content-Type':  'application/application/x-www-form-urlencoded'
};

推荐阅读