【问题标题】:Ionic 1 AngularJS HTTP post vs. Ionic 3 Angular HTTP postIonic 1 AngularJS HTTP 帖子与 Ionic 3 Angular HTTP 帖子
【发布时间】:2017-10-30 06:40:43
【问题描述】:

我在 Ionic 1 AngularJS 的组合中工作了很多,但在进入趋势后,Ionic 3 Angular 在简单的 HTTP post 请求本身方面遇到了一些问题。

让我解释一下场景,请在下面找到。

app.module.ts

import { HttpModule} from '@angular/http';

@NgModule({

imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp),
    HttpModule
  ]
})

login.ts

import {Http, Headers, RequestOptions} from '@angular/http';

let link = 'http://demo.mydomain.com/myservice/login';

var headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Access-Control-Allow-Origin', 'http://localhost');
headers.append('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
headers.append('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
headers.append('Access-Control-Allow-Credentials', 'true');

let options = new RequestOptions({headers: headers});

let postParams = JSON.stringify({"password":this.passCode, "userName":this.userName});

this.http.post(link, postParams, options)
.subscribe(data => {
    alert("data");
}, error => {
    alert("error");
});

当使用 ionic serve 在浏览器中耗尽时,得到以下响应。

Failed to load http://demo.mydomain.com/myservice/login: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8105' is therefore not allowed access. The response had HTTP status code 400.

根据我的理解,如果是基于 CORS 的问题,在安装 Chrome CORS 插件后也会出现同样的问题。

即使我尝试使用 ionic cordova run android 直接运行 Android 手机,这也太出错了。

【问题讨论】:

  • 该更新显示问题中未实际包含的代码错误,这不是很有帮助。如果人们想查看旧版本,他们可以查看历史;您应该重写问题以与代码的更新版本一致它的错误。另请注意,它是withCredentials,每个the documentation

标签: angular cordova http ionic-framework ionic3


【解决方案1】:
import {Http, Headers, RequestOptions} from '@angular/http';

let link = 'http://demo.mydomain.com/myservice/login';

var headers = new Headers();
headers.append("Accept", 'application/json');
let postParams = JSON.stringify({"password":this.passCode, "userName":this.userName});

this.http.post(link, postParams, {headers: headers, WithCredentials:true})
.subscribe(data => {
    alert("data");
}, error => {
    alert("error");
});

在我的 ionic 3 应用程序中,这么多代码在 http post 方法中对我有用。

【讨论】: