android - 在 Ionic 2 中进行 HTTP POST 调用会给出禁止响应

标签 android cordova ionic-framework ionic2 cordova-plugins

我只是想在我的 IONIC 2 项目中进行 http post 调用。当我运行 ionic serve 时,它工作正常。但是当我运行 ionic run anroid 在我的设备上运行它时,它会给我 403(禁止)响应。

这是我的 PaymentService.ts,其中进行了 http 调用

import {Http, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';

@Injectable()
export class PaymentService {
static get parameters() {
    return [[Http]];
}

constructor(private http:Http) {}

postToPaymentApi(data) {
    let headers: Headers = new Headers()
    headers.set('Content-type', 'application/x-www-form-urlencoded')
    let options = new RequestOptions({headers: headers})

    var response = this.http.post("http://test/url",data,options).map(res => res.json());
    return response;
   }
 }
}

为了克服这个问题,我尝试了几种方法,比如

  1. 运行cordova plugin add cordova-plugin-whitelist
  2. 在我的 config.xml 中添加了这一行 <meta http-equiv="Content-Security-Policy" content="default-src *; img-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
  3. 点击此链接 -> https://github.com/apache/cordova-plugin-whitelist添加<access origin>作为 *,<allow-navigation> , <allow-intent>具有指定属性的标签。
  4. 尝试添加此处提到的 proxyUrl http://blog.ionic.io/handling-cors-issues-in-ionic/

但就我而言,上述解决方案均无效。

当我从我的 android 设备点击 post 调用时,我收到以下错误响应:

{"_body":"",
"status":403,
"ok":false,
"statusText":"Forbidden",
"headers":{"Date":["Wed","30 Nov 2016 09:28:53 GMT"],
"Content-Length":["0"]},
"type":2,
"url":"http://test/url"}

我有以下 ionic 信息:

Cordova CLI: 6.4.0 
Ionic Framework Version: 2.0.0-rc.3
Ionic CLI Version: 2.1.12
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.45
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Linux 4.4
Node Version: v7.2.0
Xcode version: Not installed

谁有解决办法?

提前致谢。

最佳答案

你能试试这个例子吗?您确定要发送正确的 header 吗

postToPaymentApi(data) {
   let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });

   return new Promise(resolve => {
      this.http.post('http://test/url',data, {headers: headers })
         .subscribe(respond => {
           console.log(respond);       
         });   
   });        
}

关于android - 在 Ionic 2 中进行 HTTP POST 调用会给出禁止响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40886886/

相关文章:

android - 无法解析符号 AppCompatActivity - 无法识别支持 ​​v7 库?

android - 从设备应用程序调用 http api

android - 在 Ionic 4 Android 应用程序中打开键盘会将背景图像向上移动

android - 在不使用媒体查询的情况下,在横向和纵向模式下保持图像的高度和宽度相同

android - 更改 AlertDialog 的标题标题

android - Android 上的祝贺屏幕

java - 构建时出现 Cordova 插件错误,源 1.6 不支持菱形运算符使用源 7

android - 谷歌地图应用程序适用于 Android 9.0 但不低于

javascript - 添加到 Angular 列表功能

ionic-framework - 如何将 Ionic CLI 与 pnpm 一起使用