简体   繁体   中英

Ionic 1 AngularJS HTTP post vs. Ionic 3 Angular HTTP post

I was worked much in the combination of Ionic 1 AngularJS, but after entered into the trend Ionic 3 Angular faced some issues in simple HTTP post request itself.

Let me explain the scenario please find below.

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");
});

While running out in the browser using ionic serve getting below response.

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.

As per my understanding if it's CORS based issues after installed the Chrome CORS plugin as well getting same issues.

Even I tried the direct running for the Android phone using ionic cordova run android that's too getting error block.

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");
});

In my ionic 3 application this much of code has worked for me in http post method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM