我有一个 Ionic 3 应用程序。我最近添加了iOS平台。
当我在 iOS(模拟器和设备)上运行它时,所有具有标头的服务器请求都失败,并出现错误“Response with status: 0 for URL: null”。在 Android 上,这些请求可以正常工作。
如果我在没有标头的情况下执行请求,我会从服务器获得预期的响应。
我知道问题出在WKWebView和CORS上。服务器已正确配置 CORS。我用@angular/http模块来做请求。
让我们看一些代码。
这是我向服务器发出请求的提供者:
import { Injectable } from '@angular/core';
import { Content } from 'ionic-angular';
import { Http, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { HTTP } from '@ionic-native/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Globalization } from '@ionic-native/globalization';
import { Globals } from '../providers/globals';
...
/// Here we have one example Request (it's inside a method)
/// Here I create the URL for the request
let url = this.server_url + this.server_functions.doSearch;
/// Now I create the Headers for the Request
let headers = new Headers();
/// As You can see, I have tried to pass diferent headers to server
// headers.append("Access-Control-Allow-Origin","*");
// headers.append("Origin", "https://localhost:8080");
// headers.append("Access-Control-Allow-Methods","POST, GET, OPTIONS, PUT");
// headers.append("Accept","application/json");
// headers.append("Content-Type","application/json; charset=utf-8");
/// If the user is logged in I have to send this headers to server
if ( !this.globals.guestMode ) {
headers.append("TokenAuth", this.globals.getLogRegData()["TokenAuth"]);
headers.append("IdAuth", this.globals.getLogRegData()["IdAuth"]);
}
/// And here we start the GET Request
this.http.get( url, { headers: headers } ).map(res => res.json()).subscribe(
data => {
// console.log( JSON.stringify(data) );
callback( data );
},
err => {
console.log("ELOL: "+err);
}
);
另一方面,我决定尝试使用 @ionic-native/http 模块(正如您在导入中看到的那样)以避免 WKWebView 和 CORS 问题,但是当我用它发出请求时,我收到了这个错误:
WARN: Native: tried calling HTTP.get, but the HTTP plugin is not installed.
WARN: Install the HTTP plugin: 'ionic cordova plugin add cordova-plugin-advanced-http'
这就是我使用本机插件执行请求的方式:
this.httpnative.get(url, {}, {})
.then(data => {
console.log(data.status);
console.log(data.data); // data received by server
console.log(data.headers);
})
.catch(error => {
console.log(error.status);
console.log(error.error); // error message as string
console.log(error.headers);
});
这是我的 app.module.ts 的一个片段:
import { HttpModule } from '@angular/http';
import { HTTP } from '@ionic-native/http';
...
@NgModule({
...
imports: [
...
HttpModule,
HTTP,
...
],
})
我希望有人能给我一些启示,因为我迷失在 Ionic 的道路上。
谢谢你。