Nothing happens when trying a POST request to a WebService


#1

Hi there,

I’m facing a problem (yes again :)) with Http usage.
I’m trying to post something on a Symfony2 Route.

Following the Angular2 doc, I set their code, unfortunately nothing happens when I’m executing it, no error in console, nothing …
I’ve tried to call the URL in my browser, and no route troubles…

Here my code :

// ... Other imports
import {Component, View, Injectable} from '@angular/core';
import {Http, Headers, RequestOptions, Response} from '@angular/http';
// ... Other imports

@Page({
  templateUrl: 'build/pages/diagnostic/first/first.html',
  directives: [FORM_DIRECTIVES]
})

@Injectable()
export class FirstPage {
	
	firstForm: ControlGroup;
	firstName: AbstractControl;
	lastName: AbstractControl;
	nav: NavController;
	userCreateUrl = 'http://my-amazing-url';
	http: Http;

	static get parameters() {
		return [[NavController], [NavParams], [FormBuilder], [Http]];
	}

	constructor(nav: NavController, navParams: NavParams, fb: FormBuilder, http: Http) {
		this.nav = nav;
		this.http = http;
                // ....

	}

	dummyPost() {
		let body = JSON.stringify({ "foo":"bar" });
	        let headers = new Headers({ 'Content-Type': 'application/json' });
	        let options = new RequestOptions({ headers: headers });
	        return this.http.post(this.userCreateUrl, body, options)
                        .map(this.extractData)
                        .catch(this.handleError);
	}

	private extractData(res: Response) {
		let body = res.json();
		console.log(body);
		return body.data || {};
	}

	private handleError (error: any) {
		console.log("error");
	}

//.......

Could you help me please ?

Thanks,


#2

Hey there,

The HTTP service does not process your request until you call .subscribe().

To correct your function, it should be something like this:

dummyPost() {
	let body = JSON.stringify({ "foo":"bar" });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });
        return this.http.post(this.userCreateUrl, body, options)
                    .map(this.extractData)
                    .subscribe(
                      data => console.log("Got data", data),
                      error => console.error("Got error", error)
                    );
}

#3

Hi,

Thank you for your answer.
I’ve something happened now, but “XMLHttpRequest cannot load http://my_webservice_target. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://my_ip:8100’ is therefore not allowed access.”

Sorry I’m newbie on Ionic :confused:

have an idea please ?

Thanks :slight_smile:


#4

That error is very common when doing XHR/AJAX requests. It isn’t something ionic or angular specific. It probably has something to do with the remote server you are trying to access.

Sometimes this error occurs only in the browser, but disappears when you’re running the app natively on a device.

If the issue occurs only in the browser, download the CORS plugin for Chrome/Firefox. You can configure that browser plugin to only intercept your connections to a specific server, or to intercept everything (not recommended, causes issues with some websites, like FB, Gmail … etc)


#5

Thank you, I’ve edited my answer as same as you answered yourself :slight_smile:

I’ve “XMLHttpRequest cannot load http://webservice_host. Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://my_ip:8100’ is therefore not allowed access.”

Sorry for newby-ism :slight_smile:


#6

No worries, I edited my reply as well just now haha.

See this for more information about CORS: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

This is the plugin that I personally use on Chrome: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

Edit: if you are using an ExpressJS server in the backend, try cors npm package. You can plug it right into your Express server and it will solve your issue.


#7

Thank you, I’ll try right now.

I’m using a Symfony2 (PHP) backend server :slight_smile:

Oh it works really fine !
Thanks a lot :smile:


#8

I used that before. Then switched to Slim Framework. Then I switched to ExpressJS. I gotta tell you it’s much faster and easier to deal with.

If you’re sticking with Symfony, here’s a plugin for CORS: https://github.com/nelmio/NelmioCorsBundle


#9

Yeah I know, unfortunately, I did not have choice of the backend server technology :confused:


#10

Ahh I see.

Well when you do have the choice, you should use Express :smiley:

Just recently I started experimenting with Express + TypeScript. It’s so clean and organized IMO. Also, I get to stick to the same language as my front-end (Angular2)


#11

For my part, I’ve had a heart stroke for MeteorJS :slight_smile:

But, I’ll try Express next time, thank you ! :smiley:


#12

I gave MeteorJS a day, couldn’t figure it out. Decided to leave it alone for now.

I trust that Angular2 will compete well with Meteor and other frameworks out there.